Public inheritance : Inheritance « Class « C++






Public inheritance

Public inheritance
  
#include <iostream>
using namespace std;

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

class DerivedClass : public BaseClass {
  int k;
public:
  // DerivedClass may access BaseClass's i and j
  void setk() { 
     k = i*j; 
  }

  void showk() { 
     cout << k << endl; 
  }
};

int main()
{
  DerivedClass ob;

  ob.set(2, 3);
  ob.show();   

  ob.setk();
  ob.showk();

  return 0;
}


           
         
    
  








Related examples in the same category

1.Three level public inherianceThree level public inheriance
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