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.
Updated on: 2025-04-21T18:31:11+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements