English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In object-oriented programming, we can inherit the features of the parent class. The parent class is called the base class, and the child class is called the derived class. The derived class can inherit data members and member functions of the base class.
If the data members are public, they can be accessed through the derived class, the same class, and outside the class. If the data members are protected, they can only be accessed by the derived class and the same class, but they cannot be accessed outside the class. If the data members are private, they can only be accessed by the same class.
This is C ++Inheritance example in the language,
#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 value: " << d.x << endl; cout << "Base class data member value: " << d.a << endl; return 0; }
Output Result
Derived class data member value : 20 Base class data member value : 10
In the above program, the derived class inherits the base class and its data members. Create a derived class object d and use it to call the data members of the base class and the derived classes a and x. However, it cannot access the base class variables b and c, which are protected and private, because if we try to access them, it will display an error.
Derived d; d.a =; 10; d.x =; 20;