How to Override a Base Class Method in a Derived Class in C++?
Last Updated :
21 Feb, 2024
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++
#include <iostream>
using namespace std;
class Person {
public :
virtual void greet()
{
cout << "Person: Hello, there! \n" ;
}
};
class AngryPerson : public Person {
public :
void greet() override
{
cout << "Angry Person: Hello, looser! \n" ;
}
};
int main()
{
Person p;
AngryPerson ap;
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.
Share your thoughts in the comments
Please Login to comment...