Open In App

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

Last Updated : 21 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Function overriding is a concept in object-oriented programming languages, in which a function/method of a parent class is redefined in its child class to change its behavior for the objects of the child class. In this article, we are going to learn how to override a base class function in a derived class in C++.

Override Inherited Methods in C++

In C++, you can override a base class function in a derived class by declaring a function with the same signature in the derived class. Also, ensure that the base class function is declared as virtual function to enable dynamic binding.

C++ Program to Override a Base Class Function in a Derived Class

C++




// C++ Program to Override a Base Class Function in a
// Derived Class
#include <iostream>
using namespace std;
  
// Base class Person
class Person {
public:
    // Virtual function to greet
    virtual void greet()
    {
        cout << "Person: Hello, there! \n";
    }
};
  
// Derived class AngryPerson inheriting from Person
class AngryPerson : public Person {
public:
    // Override the greet function to provide a different
    // greeting
    void greet() override
    {
        cout << "Angry Person: Hello, looser! \n";
    }
};
  
// Driver Code
int main()
{
    // Create objects of both classes
    Person p;
    AngryPerson ap;
  
    // Call the greet function for both objects
    p.greet();
    ap.greet();
    return 0;
}


Output

Person: Hello, there! 
Angry Person: Hello, looser! 

Note: It is recommended to use the override keyword to make sure that the user have not forgotten to declare the base class version of the function as virtual.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads