原文地址:http://www.cnblogs.com/krisdy/archive/2009/06/11/1501390.html
当创建一个派生类的对象时,系统首先自动创建一个基类对象,也就是说,在调用派生类构造函数创建派生类对象之前,系统首先调用基类的构造函数创建基类对象。当派生类对象生命期结束时,首先调用派生类的析构函数,然后调用基类的析构函数。简而言之,就是说,构造函数:基类->派生类。析构函数:派生类->基类。
这个我们完全可以通过一个小程序来说明:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"A(Based Class) constructor is called"<<endl;
}
~A()
{
cout<<"A(Based Class) destructor is called"<<endl;
}
};
class B:public A
{
public:
B()
{
cout<<"B(Derived Class) constructor is called"<<endl;
}
~B()
{
cout<<"B(Derived Class) destructor is called"<<endl;
}
};
int main()
{
B b1;
return 0;
}
下面分别给出一个隐式和显式调用的例子:
#include <iostream>
using namespace std;
class A
{
public:
A(int x = 0,int y = 0)
{
a = x;
b = y;
}
private:
int a;
int b;
};
//基类A有默认的构造函数,可以隐式调用
class B:public A
{
public:
B(int z = 0)
{
c = z;
}
private:
int c;
};
int main()
{
B b1;
return 0;
}
#include <iostream>
using namespace std;
class A
{
public:
A(int x,int y)
{
a = x;
b = y;
}
private:
int a;
int b;
};
//基类A没有默认的构造函数,其现有的构造函数需要传递参数,通过
//派生类构造函数调用A构造函数时必须如下显式调用
class B:public A
{
public:
B(int x,int y,int z):A(x,y)
{
c = z;
}
private:
int c;
};
int main()
{
B b1(1,2,3);
return 0;
}