Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

In C++, dynamic binding and polymorphism will be achieved when member

function will be virtual. A virtual function is a member function in a base class


that can be overridden by a derived class. When a virtual function is called,
the compiler does not know at compile time which version of the function will
be executed. Instead, the compiler defers the decision to runtime. This is what
allows for dynamic binding and polymorphism.

Here is an example of how to use virtual functions in C++:

C++
class Animal {
public:
virtual void speak() = 0; // pure virtual function
};

class Dog : public Animal {


public:
void speak() {
cout << "Woof!" << endl;
}
};

class Cat : public Animal {


public:
void speak() {
cout << "Meow!" << endl;
}
};

int main() {
Animal* animal = new Dog();
animal->speak(); // This will print "Woof!"

animal = new Cat();


animal->speak(); // This will print "Meow!"
}
Use code with caution. Learn more
content_copy

In this example, the speak() function is declared as a virtual function in the


Animal class. This means that it can be overridden by a derived class. The Dog
and Cat classes both override the speak() function to provide their own
implementation.

When the speak() function is called in the main() function, the compiler does
not know at compile time which version of the function will be executed.
Instead, the compiler defers the decision to runtime. At runtime, the compiler
will determine the type of the object that is passed to the speak() function, and
then it will execute the appropriate version of the function.

This is how dynamic binding and polymorphism are achieved in C++. By using
virtual functions, we can create objects that can behave differently depending
on their type.

You might also like