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

C++ProgrammingServer Side Programming

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();
raja
Published on 08-Nov-2018 10:53:01
Advertisements