C++ Virtual Function
In C++, a virtual function is a function that is declared as virtual in a base class and can be overridden by a derived class. Virtual functions are used to implement polymorphism in C++.
When a function is declared as virtual in a base class, it means that the function can be overridden by a derived class. When a derived class overrides a virtual function, it provides its own implementation of the function, which is used when the function is called on an object of the derived class.
Here's an example:
refe:ot rtheitroad.comclass Animal { public: virtual void speak() { std::cout << "Animal speaks." << std::endl; } }; class Dog : public Animal { public: void speak() override { std::cout << "Dog barks." << std::endl; } }; int main() { Animal* a = new Animal(); a->speak(); // "Animal speaks." Animal* b = new Dog(); b->speak(); // "Dog barks." }
In this example, we have a base class Animal
with a virtual method speak()
. We also have a derived class Dog
, which overrides the speak()
method with its own implementation.
In the main()
function, we create two objects of type Animal
and Dog
, but we assign the Dog
object to a pointer of type Animal
. This allows us to call the speak()
method on both objects, even though they're of different types. When we call speak()
on the Animal
object, we get the base class implementation of the method. When we call speak()
on the Dog
object, we get the derived class implementation of the method.
Note that the override
keyword is used to indicate that the speak()
method in the Dog
class is intended to override the speak()
method in the Animal
class. This is not strictly necessary, but it is good practice to make it clear that the derived class is intentionally overriding a virtual function from the base class.