What all is inherited from parent class in C++?

C++ProgrammingServer Side Programming

In the object-oriented programming, we can inherit the characteristics of parent class. Parent class is known as base class while child class is known as derived class. The derived class can inherit data members, member functions of base class.

If the data members are public, they can be accessed by derived class, same class and outside the class. If data members are protected, they can be accessed by derived and same class only, but outside the class, they can not be accessed. If data members are private, only same class can access them.

Here is an example of inheritance in C++ language,

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Base {
   public: int a;
   protected: int b;
   private: int c;
};
class Derived : public Base {
   public: int x;
};
int main() {
   Derived d;
   d.a = 10;
   d.x = 20;
   cout << "Derived class data member vale : " << d.x << endl;
   cout << "Base class data member value : " << d.a << endl;
   return 0;
}

Output

Derived class data member vale : 20
Base class data member value : 10

In the above program, derived class is inheriting the base class and its data members. Derived class object d is created and used to call the data members of base and derived class a and x. But it can not access the variable b and c of base class because they are protected and private, It will show errors if we will try to access them.

Derived d;
d.a = 10;
d.x = 20;
raja
Published on 05-Nov-2018 12:20:28
Advertisements