How to call a parent class function from derived class function in C++?


The following is an example to call parent class function from derived class function.

Example

 Live Demo

#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;
}

Output

The derived class d1 function is called.
The parent class p1 function is called.

In the above program, a parent class p1 is created and a function first() is defined in it.

class p1 {
   public:
   void first() {
      cout << "\nThe parent class p1 function is called.";
   }
};

A derived class is created, which is inheriting parent class p1 and overloading the parent class function first().

class d1 : public p1 {
   public:
   void first() {
      cout << "The derived class d1 function is called.";
      p1::first();
   }
};

The function of d1 class is calling the function of p1 class.

p1::first();

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements