
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Call Parent Class Function from Derived Class in C++
In the OOPs concept of C++, the parent class represents the root of the hierarchy while the derived class is inherited from the parent class. The derived class is presented using the scope resolution operator (::). The derived class is also known as the child class or subclass.
What is Parent Class?
The parent class is also called a base class used to design the structure of variable and function initialization based on access specifiers (private, public, and protected).
Syntax
Following is the syntax of parent class in C++:
class ParentClass { // Access specifiers: public, protected, private public: // Public members (accessible anywhere in the program) void publicMethod() { cout << "Public method\n"; } protected: // Protected members (accessible within this class and derived classes) int protectedVar; private: // Private members (accessible within this class) string privateVar; };
What is Derived Class?
The derived class inherited the properties and behavior from the parent or based class.
Syntax
Following is the syntax of derived class in C++:
class Derived : public Base { public: void functionName() { // Call parent class function Base::functionName(); // Derived class implementation } };
Calling Parent Class Function from Derived Class
In this example, we demonstrates the method overriding in inheritance. The derived class d1 overrides the first() function of its base class p1, but also explicitly calls the base class using p1::first(). When d.first() is called in main(), it display the message from d1::first() followed by the message from p1::first().
#include <bits/stdc++.h> using namespace std; class p1 { public: void first() { cout << "\nThe parent class p1 function is called."; } }; class d1 : public p1 { public: void first() { cout << "The derived class d1 function is called."; p1::first(); } }; int main() { d1 d; d.first(); return 0; }
The above program produces the following result:
The derived class d1 function is called. The parent class p1 function is called.