In C++, a virtual function is a member function of a base class that can be overridden in a derived class. When you declare a function as virtual in a base class, you're telling the compiler to create a "virtual table" that maps the virtual function to the correct implementation in the derived class. This allows you to write code that works with objects of the base class type, but calls the overridden version of the function in the derived class.
Here's an example to illustrate how virtual functions work:
c++class Animal {
public:
virtual void makeSound() {
cout << "Generic animal sound" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() {
cout << "Bark!" << endl;
}
};
int main() {
Animal *ptr = new Dog();
ptr->makeSound(); // Calls Dog::makeSound()
delete ptr;
return 0;
}
In this example, we have a base class called Animal
with a virtual function called makeSound()
. We also have a derived class called Dog
that overrides the makeSound()
function with its own implementation. In the main()
function, we create a pointer to an Animal
object and assign it to a Dog
object. When we call the makeSound()
function on this pointer, the overridden version in Dog
is called instead of the version in Animal
.
Virtual functions are useful when you have a base class that defines a generic behavior, but you want to allow derived classes to customize that behavior in their own way. By making the function virtual, you can ensure that the correct version of the function is called at runtime, depending on the actual type of the object.
Comments
Post a Comment