Hierarchical inheritance

C++ Hierarchical Inheritance Syntax

class A // base class
{
    ..............
};
class B : access_specifier A // derived class from A
{
    ...........
 } ;
 class C : access_specifier A // derived class from A
 {
    ...........
 } ;
 class D : access_specifier A // derived class from A
 {
     ...........
 } ;

C++ Hierarchical Inheritance Example

// hierarchial inheritance.cpp
#include <iostream> 
using namespace std;

class A //single base class
{
    public:
 	int x, y;
 	void getdata()
 	{
   	    cout << "\nEnter value of x and y:\n"; cin >> x >> y;
 	}
};
class B : public A //B is derived from class base
{
    public:
 	void product()
 	{
 	    cout << "\nProduct= " << x * y;
 	}
};
class C : public A //C is also derived from class base
{
    public:
 	void sum()
 	{
        cout << "\nSum= " << x + y;
 	}
};
int main()
{
    B obj1;          //object of derived class B
    C obj2;          //object of derived class C
    obj1.getdata();
    obj1.product();
    obj2.getdata();
    obj2.sum();
    return 0;
}  //end of program


Output

Enter value of x and y:
2
3
Product= 6
Enter value of x and y:
2
3
Sum= 5

Explanation
In this example, there is only one base class A from which two class B and C are derived.

Both derived class have their own members as well as base class members.

The product is calculated in the derived class B, whereas, the sum is calculated in the derived class C but both use the values of x and y from the base class.

Comments

Popular posts from this blog

BPSC 66th Exam Interview 2022: बीपीएससी 66वीं परीक्षा के साक्षात्कार 18 जुलाई को, कॉल लेटर जारी

पिता को नौकरी दिलाने में पुत्र ने अपना करियर दांव पर लगायाः होमगार्ड बहाली में बाप के बदले दौर लगा रहा बेटा गिरफ्तार