C++ Inheritance - 3
C++ Inheritance - 3
C++ Tutorials
If a single class is derived from one base class then it is called single inheritance. In C++ single inheritance
base and derived class exhibit one to one relation.
As shown in the gure, in C++ single inheritance only one class can be derived from the base class. Based on
the visibility mode used or access speci er used while deriving, the properties of the base class are derived.
Access speci er can be private, protected or public.
www.trytoprogram.com/cplusplus-programming/single-inheritance/ 1/5
10/13/2020 C++ Single Inheritance (With Examples) - Trytoprogram
Click here to learn in detail about access speci ers and their use in inheritance
www.trytoprogram.com/cplusplus-programming/single-inheritance/ 2/5
10/13/2020 C++ Single Inheritance (With Examples) - Trytoprogram
// inheritance.cpp
#include <iostream>
using namespace std;
class base //single base class
{
public:
int x;
void getdata()
{
cout << "Enter the value of x = "; cin >> x;
}
};
class derive : public base //single derived class
{
private:
int y;
public:
void readdata()
{
cout << "Enter the value of y = "; cin >> y;
}
void product()
{
cout << "Product = " << x * y;
}
};
int main()
{
derive a; //object of derived class
a.getdata();
a.readdata();
a.product();
return 0;
} //end of program
www.trytoprogram.com/cplusplus-programming/single-inheritance/ 3/5
10/13/2020 C++ Single Inheritance (With Examples) - Trytoprogram
Sign Up
Output
Explanation
In this program class derive is publicly derived from the base class base . So the class derive inherits all
the protected and public members of base class base i.e the protected and the public members of base
class are accessible from class derive .
However private members can’t be accessed, although, we haven’t used any private data members in the
base class.
With the object of the derived class, we can call the functions of both derived and base class.
www.trytoprogram.com/cplusplus-programming/single-inheritance/ 4/5
10/13/2020 C++ Single Inheritance (With Examples) - Trytoprogram
www.trytoprogram.com/cplusplus-programming/single-inheritance/ 5/5