Saturday, September 17, 2011

Constructor and Destructor of derived Class

Example of Constructor and Destructor of derived Class:



#include <iostream>

using namespace std;

class BASE{
public:
BASE(int x, int y, int z);
~BASE();
void doit();
int a;
protected:
int b;
string Im;
private:
int c;
};



BASE::BASE(int x, int y, int z)
:a(x), b(y), c(z){
Im = "Base Class";
}

BASE::~BASE(){
cout << "BASE's destructor! " << Im << endl;
}

void BASE::doit(){
cout << "BASE::doit()" << endl;
cout << a << endl;
cout << b << endl;
cout << c << endl;
}

class DERIVED:public BASE{
public:
DERIVED(int x, int y, int z, int w);
~DERIVED();
void doit();
private:
int d;
};

DERIVED::DERIVED(int x, int y, int z, int w)
:BASE(x, y, z), d(w){
Im = "Derived Class";
}

DERIVED::~DERIVED(){
cout << "DERIVED's destructor! " << Im << endl;
}

void DERIVED::doit(){
cout << "DERIVED::doit()" << endl;
BASE::doit();
cout << d << endl;
}

int main()
{

BASE base(1, 2, 3);
base.doit();
DERIVED derived(4, 5, 6, 7);
derived.doit();
return 0;
}




Constructor and Destructor of derived Class




No comments:

Post a Comment