Multilevel Inheritance in C++.

Multilevel Inheritance: It is the process of deriving a class from another derived class.
Multilevel Inheritance

//Program to implement Multilevel Inheritance...
#include <iostream.h>
#include <conio.h>
class base //single base class
{
  public:
  int x;
  void getdata()
  {
    cout << "Enter value of x= "; cin >> x;
  }
};
class derive1 : public base // derived class from base class
{
  public:
  int y;
  void readdata()
  {
      cout << "\nEnter value of y= "; cin >> y;
  }
};
class derive2 : public derive1   // derived from class derive1
{
  private:
  int z;
  public:
  void indata()
  {
    cout << "\nEnter value of z= "; cin >> z;
  }
  void product()
  {
      cout << "\nProduct= " << x * y * z;
  }
};
int main()
{
     derive2 a;      //object of derived class
     a.getdata();
     a.readdata();
     a.indata();
     a.product();
     return 0;

Expected Output:-

Enter value of x= 2
Enter value of y= 3
Enter value of z= 3
Product= 18

//Program to implement Multilevel Inheritance...
#include <iostream.h>
#include <conio.h>

class A
{
    public:
      void display()
      {
          cout<<"Base class content.";
      }
};
class B : public A
{
};
class C : public B
{ 
};
int main()
{
    C obj;
    obj.display();
    return 0;
}

Expected Output:-

Base class content.

//Program to implement Multilevel Inheritance...
#include <iostream.h>  
#include <conio.h>
class A  
{  
    protected:  
     int a;  
    public:  
    void get_a(int n)  
    {  
        a = n;  
    }  
};   
class B  
{  
    protected:  
    int b;  
    public:  
    void get_b(int n)  
    {  
        b = n;  
    }  
};  
class C : public A,public B  
{  
   public:  
    void display()  
    {  
        std::cout << "The value of a is : " <<a<< std::endl;  
        std::cout << "The value of b is : " <<b<< std::endl;  
        cout<<"Addition of a and b is : "<<a+b;  
    }  
};  
int main()  
{  
   C c;  
   c.get_a(10);  
   c.get_b(20);  
   c.display();  
  
    return 0;  
}  
Expected Output:-

The value of a is : 10
The value of b is : 20
Addition of a and b is : 30

Post a Comment

Previous Post Next Post