Monday, March 4, 2013

OOCP (CPP) : Example # 15 : CPP Inheritance Parameterised constructor

OOCP (CPP)  :  Example #  15 : CPP Inheritance Parametrized constructor

* Lets start learning about cpp inheritance.
* Following example is simple inheritance : Single Inheritance consist of one base class and one derived class.
* This example will demonstrate about how to pass parameter to constructor while using inheritance

//Written by Latest Technology Guide    
//Title : OOCP (CPP)  :  Example #  
15 : CPP Inheritance Parameterised constructor

#include <iostream.h>
#include <conio.h>

class B
{
private:
int a;
protected:
void printinfo();
static int i; //Static member must be protected or public
public:
// B(int x=0) : a(x) {} //Short method to initialize
// Or
B(int x=0)
{
a = x;
cout << "Base class constructor called..." << ++i << endl;
cout << "Value of A : " << a << endl;
}
~B()
{
cout << "Base class Destructor called..." << --i << endl;
}
void print()
{
B :: printinfo();
}
};

int B :: i =0;

void B :: printinfo()
{
cout << "A ==> " << a;
cout << " , Size of Base class B is : " << sizeof(this->a) << endl;
}

class D : public B
{
private:
int b;
public:
D(int y=0) : B(y), b(y+10)
// Or
// D(int y=0)
{
// B(y);
cout << "Derived class construtor called..." << ++i << endl;
// b = y+10;

}
~D()
{
cout << "Derived class destructor called... " << --i << endl;
}
void print();
};
void D :: print()
{
B :: printinfo();
cout << "B ==> " <<  b;
cout << " , Size of Derived class D is : " << sizeof(this->b) << endl;
}

//=================================================
// Void Main
//=================================================
void main()
{
clrscr();
B b(100); //With parameter initialize by 100 : base class only
B b1; //Without parameter by 0
D d(200); //Base class obj construct first then derived: a=200 b=210
D d1; //a = 0  b=10
cout << endl << endl;
b.print();
d.print();
cout << endl << endl;
cout << "Sizeof Base    class is : " << sizeof(b) << endl;
cout << "Sizeof Derived class is : " << sizeof(d) << endl;

getch();
}


Output:
* You will find output as you have entered value.

--------------------------------------------------------------------------------
OOCP (CPP)  :  Example #  15 : CPP Inheritance Parameterised constructor

* Example demonstrate how to create your first inheritance program using cpp example 2.
* in example B stands for Base Class while D stands for Derived class.


Note: 
All programs are developed and tested using Turbo C++ 3.0 under Windows XP. We just want to provide guidelines to the users. If you are using any other Compiler or other operating system they you need to modify this program as per your requirements. 

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. .thank you for sharing useful post.
    c++ programming tutorial
    welookups

    ReplyDelete