Wednesday, February 6, 2013

the order of constructor and destructor


#include<iostream>
#include<string>

using namespace std;

class A
{
protected:
A(){printf("constructor A\n");}
A(const A& a){printf("copy constructor A\n");}
A& operator=(const A& a){printf("assignment operator A\n");}
virtual ~A(){clean();}
virtual void Fa()=0;
virtual void Ga(){printf("destructor A\n");};
void clean(){Ga();}
};

class B : virtual public A
{
public:
B() {printf("constructor B\n");}
B(const B& b){printf("copy constructor B\n");}
B& operator=(const B& b){printf("assignment operator B\n");return (*this);}
~B(){printf("destructor B\n");}
private:
virtual void Fa()
{
puts("Fa-B");
}
virtual void Ga()
{
printf("Ga-B");
Fa();
}
};

void test()
{
B b,c=b; //this is copy constructor!!
c=b;  //this is assignment operator!!
}

output: constructor A
constructor B
constructor A
copy constructor B
assignment operator B
destructor B
destructor A
destructor B
destructor A



No comments:

Post a Comment