Examples of Function Overriding in C++
Example 1: C++ Program to Call Overridden Function From Derived Class
// C++ program to demonstrate function overriding
// by calling the overridden function
// of a member function from the child class
#include <iostream>
using namespace std;
class Parent {
public:
void w3wiki_Print()
{
cout << "Base Function" << endl;
}
};
class Child : public Parent {
public:
void w3wiki_Print()
{
cout << "Derived Function" << endl;
// call of original function
Parent::w3wiki_Print();
}
};
int main()
{
Child Child_Derived;
Child_Derived.w3wiki_Print();
return 0;
}
Output
Derived Function Base Function
Example 2: C++ Program to Call Overridden Function Using Pointer
// C++ program to access overridden function using pointer
// of Base type that points to an object of Derived class
#include <iostream>
using namespace std;
class Parent {
public:
void w3wiki()
{
cout << "Base Function" << endl;
}
};
class Child : public Parent {
public:
void w3wiki()
{
cout << "Derived Function" << endl;
}
};
int main()
{
Child Child_Derived;
// pointer of Parent type that points to derived1
Parent* ptr = &Child_Derived;
// call function of Base class using ptr
ptr->w3wiki();
return 0;
}
Output
Base Function
Example 3: C++ Program to Access of Overridden Function using Child Class Object
// C++ program to access overridden function
// in main() using the scope resolution operator ::
#include <iostream>
using namespace std;
class Parent {
public:
void w3wiki()
{
cout << "Base Function" << endl;
}
};
class Child : public Parent {
public:
void w3wiki()
{
cout << "Derived Function" << endl;
}
};
int main()
{
Child Child_Derived;
Child_Derived.w3wiki();
// access w3wiki() function of the Base class
Child_Derived.Parent::w3wiki();
return 0;
}
Output
Derived Function Base Function
Function Overriding in C++
A function is a block of statements that together performs a specific task by taking some input and producing a particular output. Function overriding in C++ is termed as the redefinition of base class function in its derived class with the same signature i.e. return type and parameters. It can be of both type: Compile Time and Runtime Polymorphism.