In this C++ tutorial, you will learn about Function Overriding, how to override functions in super class by defining a function in the child class with the same function name and same set of parameters, with examples.
C++ Function Overriding
In C++, Function Overriding is a process of overriding the base class behaviour by derived class behaviour. To override a function of base class, define a function in derived class with the same function prototype as that of in base class.
In this tutorial, we will learn how to override a function defined in base class, by defining the same function, and of course with different logic, in derived class.
Syntax
The syntax to override function printMsg() of base class A by the same function in derived class B is
class A {
public:
void printMsg(string s) {
//code
}
};
class B: public A {
public:
void printMsg(string s) {
//override code
}
};
Examples
1. Override printMsg() function in class A with the printMsg() function in class B
In the following program, we have two classes: A and B. A is base class and B is derived class of A. B inherits the properties and behaviours of A. But to override a behaviour/function printMsg() of base class, B implements the function printMsg() by itself. B is overriding the function of base class A.
C++ Program
#include <iostream>
using namespace std;
class A {
public:
void printMsg(string s) {
cout << "A : " << s << endl;
}
};
class B: public A {
public:
void printMsg(string s) {
cout << "B : " << s << endl;
}
};
int main() {
B b;
b.printMsg("Hello World");
}
Output
B : Hello World
Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned what Function Overriding is, and how to use Function Overriding to override the behaviour of base class by derived class, with the help of examples.