在C++中,派生类的构造函数内部可以显示的调用基类的构造函数,如果不显示的调用基类的构造函数,那么会默认的调用基类的默认构造函数。例如,假设基类为Item_base,定义如下:
class Item_base
{
private:
int number;
string str;
public:
Item_base()
{
cout << "the default constructor of base class is called!\n";
}
Item_base(int num,string s): number(num),str(s)
{
cout << "the constructor of base calss is called!" << endl;
}
~Item_base(){}
};
派生类定义如下所示:
class Derive_class:public Item_base
{
private:
size_t qty;
double price;
public:
Derive_class()
{
cout << "the first default constructor is called!\n";
}
Derive_class(size_t q,double p): qty(q),price(p)
{
cout << "the second constructor of derive class is called!" << endl;
}
Derive_class(int num,string s,size_t q ,double p) :qty(q),price(p)
{
cout << "the third constructor is called!\n";
Item_base(num,s);
}
};
在main函数中使用基类和派生类构造对象,代码如下所示:int main()
{
cout << "first:\n";
Item_base item;
cout << "second:\n";
Item_base new_item(4,"hello");
cout << "third:\n";
Derive_class derive;
cout << "fourth:\n";
Derive_class new_derive(5,6.2);
cout << "fifth:\n";
Derive_class new_derive2(6,"world",3,4.2);
return 0;
}
运行mian函数,输出结果为:first:
the default constructor of base class is called!
second:
the constructor of base calss is called!
third:
the default constructor of base class is called!
the first default constructor is called!
fourth:
the default constructor of base class is called!
the second constructor of derive class is called!
fifth:
the default constructor of base class is called!
the third constructor is called!
the constructor of base calss is called!
从程序运行结果可以看出,在构造派生类对象时总是先调用基类构造函数构造基类部分的对象,在派生类的构造函数中如果没有显示的调用基类的构造函数,那么派生类构造函数机会隐式的调用基类的默认构造函数。而且,在派生类的构造函数中,函数体内的代码只能对基类部分的对象进行赋值,基类对象的构造是在进入函数体内以前完成的。如果将派生类的最后一个构造函数改为如下:Derive_class(int num,string s,size_t q ,double p) :Item_base(num,s),qty(q),price(p)
{
cout << "the third constructor is called!\n";
}
那么main函数的输出将变为:first:
the default constructor of base class is called!
second:
the constructor of base calss is called!
third:
the default constructor of base class is called!
the first default constructor is called!
fourth:
the default constructor of base class is called!
the second constructor of derive class is called!
fifth:
the constructor of base calss is called!
the third constructor is called!
可见,在派生类的成员初始化列表中调用基类构造函数就可以阻止派生类构造函数隐式的调用基类默认构造函数。