C++ Overriding
C++ Overriding is a feature of object-oriented programming that allows a derived class to provide a different implementation of a virtual function defined in its base class. When a virtual function is overridden, the version of the function called is determined at runtime based on the actual type of the object being referred to, rather than the type of the pointer or reference.
Here's an example to illustrate function overriding in C++:
class Animal {
public:
virtual void makeSound() {
cout << "The animal makes a sound." << endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
cout << "The dog barks." << endl;
}
};
class Cat : public Animal {
public:
void makeSound() override {
cout << "The cat meows." << endl;
}
};
int main() {
Animal* animal1 = new Dog();
Animal* animal2 = new Cat();
animal1->makeSound(); // Calls the makeSound() function of Dog
animal2->makeSound(); // Calls the makeSound() function of Cat
delete animal1;
delete animal2;
return 0;
}
In the example above, the Animal class defines a virtual function makeSound(). The Dog and Cat classes inherit from Animal and override the makeSound() function with their own implementations.
During runtime, when the makeSound() function is called through pointers of type Animal, the appropriate version of the function is invoked based on the actual object being referred to. This is achieved through the override keyword, which ensures that the function being overridden is declared in the base class as virtual.
Function overriding allows derived classes to provide their own specialized implementation of a function defined in the base class. This enables polymorphic behavior, where different objects of derived classes can be treated as objects of the base class while executing their specific implementations of the overridden function.
Key points to remember about function overriding in C++:
The base class function must be declared as virtual.
The derived class function must have the same name, return type, and parameters as the base class function.
The override keyword is optional but recommended for clarity and to ensure that the intended overriding is taking place.
Overriding provides a powerful mechanism for designing flexible and extensible class hierarchies. It allows for customization and specialization of behavior in derived classes while leveraging the common interface provided by the base class.