C++ Function Overriding
C++ Function Overriding
In this tutorial, we will learn about function overriding in C++ with the help of
examples.
Suppose, the same function is defined in both the derived class and the based
class. Now if we call this function using the object of the derived class, the
function of the derived class is executed.
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
derived1.print();
return 0;
}
Output
Derived Function
Here, the same function print() is defined in both Base and Derived classes.
So, when we call print() from the Derived object derived1 , the print() from
Derived is executed by overriding the function in Base .
As we can see, the function was overridden because we called the function from
an object of the Derived class.
Had we called the print() function from an object of the Base class, the
function would not have been overridden.
We can also access the overridden function by using a pointer of the base class
to point to an object of the derived class and then calling the function from that
pointer.
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1, derived2;
derived1.print();
return 0;
}
Output
Derived Function
Base Function
derived2.Base::print();
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
derived1.print();
return 0;
}
Output
Derived Function
Base Function
In this program, we have called the overridden function inside the Derived class
itself.
Notice the code Base::print(); , which calls the overridden function inside the
Derived class.
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
return 0;
}
Output
Base Function
In this program, we have created a pointer of Base type named ptr . This
pointer points to the Derived object derived1 .
When we call the print() function using ptr , it calls the overridden function
from Base .
In order to override the Base function instead of accessing it, we need to use
virtual functions in the Base class.