Open In App

How to Override a Base Class Method in C++?

Last Updated : 13 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, method overriding allows us to redefine a function from a parent class (base class) in its child class (derived class) to modify its behavior for objects of the child class. In this article, we will learn how to override a base class method in the derived class in C++.

Override Inherited Method in C++

In C++, to override a base class method in a derived class, we first have to declare that function as a virtual function in the base class. After that, we can redefine this virtual function in the derived class. Declaring the function as virtual tells the compiler to use the most derived version of the function available for that object.

We can also use the override keyword in the inherited function redefinition to prevent errors.

Approach

  • Define a base class with the method we want to override using a virtual keyword.
  • Create a derived class that inherits from the base class. In the derived class, redefine the method to be overridden with the same signature (name and parameters) and use the override keyword to explicitly indicate that we intend to override the method.
  • Now, use objects of the derived class to call the overridden method and when the method is called, the implementation in the derived class will be executed instead of the base class implementation.

C++ Program to Override a Base Class Method

The below example demonstrates how we can override a base class method in a derived class in C++.

C++
// C++ Program to illustrate how to override the function of
// base class in derived class
#include <iostream>
using namespace std;

// Base class
class Animal {
public:
    virtual void makeSound()
    {
        cout << "The animal makes a sound" << endl;
    }
};

// Derived class
class Dog : public Animal {
public:
    // Overriding makeSound() function of the base class
    void makeSound() override
    {
        cout << "The dog barks" << endl;
    }
};

int main()
{
    Dog dog;
    dog.makeSound(); // Outputs: "The dog barks"
    return 0;
}

Output
The dog barks

Time Complexity: O(1)
Auxilliary Space: O(1)

Note: To enable overriding, the base class method should be declared as virtual in the base class. This enables dynamic dispatch, ensuring that the appropriate derived class method is called based on the actual type of the object at runtime.




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads