C++ Function Overriding
Function overriding in C++ occurs when a derived class redefines a method that was already defined in its base class. For overriding to work, the following conditions must be met:
- The function in the base class should be marked as
virtual
. - The derived class function must have the same name, return type, and parameters as the function in the base class.
Overriding allows the derived class to change or extend the behavior of the inherited function, which is crucial for implementing polymorphism.
Example 1: Function Overriding with Base Class Pointer
Code Example:
#include <iostream> using namespace std; // Base class // Derived class Dog // Derived class Cat int main() { // Calling the overridden functions delete animal1; return 0; |
Explanation:
In this example, the Animal
class has a speak()
function that is virtual, enabling runtime polymorphism. The derived classes Dog
and Cat
override the speak()
function with their own implementations.
- The
animal1
pointer points to aDog
object, andanimal2
points to aCat
object. - Even though both
animal1
andanimal2
are of typeAnimal*
, the appropriate method (eitherDog::speak()
orCat::speak()
) is called, thanks to dynamic dispatch, which is triggered by thevirtual
keyword in the base class.
Output:
Dog barks.
Cat meows.
Example 2: Function Overriding with Base Class Reference
Code Example:
#include <iostream> using namespace std; // Base class // Derived class Dog // Derived class Cat int main() { // Base class references // Calling the overridden functions return 0; |
Explanation:
In this example, the Animal
class function speak()
is virtual, and it is overridden in both the Dog
and Cat
classes. Instead of using pointers, we use references to refer to the objects. Even though the references are of type Animal&
, the correct version of the speak()
function is invoked based on the actual object type.
animal1
refers to aDog
object, andanimal2
refers to aCat
object.- Thanks to the
virtual
keyword, dynamic polymorphism ensures that the appropriatespeak()
function (eitherDog::speak()
orCat::speak()
) is called at runtime.
Output:
Dog barks.
Cat meows.