Friday, November 28, 2014

Simple program using inheritance C++



A simple program demonstrating inheritance

 
#include 
#include
using namespace std;
class base 
{
  int i, j;
public:
  void set(int a, int b) 
{
 i = a; j = b; 
}
  void show() 
 {
  cout << i << " " << j << "\n"; 
  }
};
class derived : public base 
{
  int k;
public:
  derived(int x) 
  {
   k = x; 
   }
  void showk() 
 { 
  cout << k << "\n"; 
  }
};
int main()
{
  derived ob(3);
  ob.set(1, 2); 
  ob.show();    
  ob.showk();   
  return 0;
}

Using protected members

 
#include 
#include
using namespace std;
class base 
{
protected:
  int i, j; 
public:
void set(int a, int b) 
{
 i = a; j = b; 
 }
 void show() 
{ 
 cout << i << " " << j << "\n"; 
 }
};
class derived : public base 
{
  int k;
public:
          void setk() 
          {
           k = i*j;
           }
 void showk() 
{ 
cout << k << "\n"; 
 }
};
int main()
{
  derived ob;
  ob.set(2, 3); 
  ob.show();    
  ob.setk();
  ob.showk();
  return 0;
}

Protected inheritance

 
#include 
#include
using namespace std;
class base 
{
  int i;
protected:
  int j;
public:
  int k;
  void seti(int a) 
  {
   i = a; 
   }
  int geti() 
 { 
   return i; 
 }
};
class derived : protected base 
{
public:
  void setj(int a) 
  {
   j = a; 
}
  void setk(int a) 
  {
   k = a; 
   }
   int getj() 
  { 
   return j; 
   }
  int getk() 
  { 
   return k; 
   }
};
int main()
{
  derived ob;
  ob.seti(10);
  cout << ob.geti(); 
  ob.k = 10; 
  ob.setk(10);
  cout << ob.getk() << ' ';
  ob.setj(12);
  cout << ob.getj() << ' ';
  return 0;
}

Multiple inheritance 

 
#include 
#include
using namespace std;
class base1 
{
protected:
  int x;
public:
  void showx() 
{
 cout << x << "\n"; 
}
};
class base2 
{
protected:
  int y;
public:
void showy() 
{
 cout << y << "\n"; 
 }
};
class derived: public base1, public base2 
{
public:
  void set(int i, int j) 
{ 
x = i; y = j; 
}
};
int main()
{
  derived ob;
  ob.set(10, 20); 
  ob.showx();     
  ob.showy();     
  return 0;
}

Calling base class's constructor in derived class

 
#include 
#include
using namespace std;
class base1 
{
protected:
  int i;
public:
  base1(int x) 
   {
    i = x;
    cout << "Constructing base1\n";
    }
  ~base1() 
   { 
    cout << "Destructing base2\n"; 
    }
};
class base2 
{
protected:
  int k;
public:
  base2(int x) 
 { 
  k = x; 
  cout << "Constructing base2\n"; 
   }
  ~base2() 
   {
    cout << "Destructing base2\n"; 
    }
};
class derived: public base1, public base2 
{
  int j;
public:
  derived(int x, int y, int z): base1(y), base2(z)
    { 
      j = x; 
       cout << "Constructing derived\n"; 
     }
  ~derived() 
    { 
      cout << "Destructing derived\n"; 
     }
  void show() 
  {
    cout << i << " " << j << " " << k << "\n"; 
  }
};
int main()
{
  derived ob(3, 4, 5);
  ob.show();  
  return 0;
}

1 comment: