Professional Documents
Culture Documents
Learn More
Learn More
C++
class Animal {
public:
virtual void speak() = 0; // pure virtual function
};
int main() {
Animal* animal = new Dog();
animal->speak(); // This will print "Woof!"
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.