Three level public inheriance : Inheritance « Class « C++






Three level public inheriance

Three level public inheriance
  
#include <iostream>
using namespace std;

class BaseClass {
protected:
  int i, j;
public:
  void set(int a, int b) { 
     i = a; 
     j = b; 
  }
  void show() { 
     cout << i << " " << j << endl; 
  }
};

// i and j inherited as protected.
class DerivedClass1 : public BaseClass {
  int k;
public:
  void setk() { 
     k = i*j; 
  } 
  void showk() { 
     cout << k << endl; 
  }
};


class DerivedClass2 : public DerivedClass1 {
  int m;              // i and j inherited indirectly through DerivedClass1.
public:
  void setm() { 
     m = i-j; 
  }
  void showm() { 
     cout << m << endl; 
  }
};

int main()
{
  DerivedClass1 object1;
  DerivedClass2 object2;

  object1.set(2, 3);
  object1.show();
  object1.setk();
  object1.showk();

  object2.set(3, 4);
  object2.show();
  object2.setk();
  object2.setm();
  object2.showk();
  object2.showm();

  return 0;
}


           
         
    
  








Related examples in the same category

1.Public inheritancePublic inheritance
2.Make field public during private inheritance
3.Demonstrate inheriting a protected base class.Demonstrate inheriting a protected base class.
4.A simple example of inheritance.A simple example of inheritance.
5.Share member variables between sub classShare member variables between sub class
6.Virtual functions retain virtual nature when inherited.Virtual functions retain virtual nature when inherited.
7.Inherit base as privateInherit base as private
8.call contructor from parent class
9.Cascade constructor and destructor call
10.Call parent constructor and pass in parameter
11.Access control under inheritance