派生类构造函数调用
Derived Class Constructor Calls
如果我有一个基类:
class Base{
...
};
和派生类
class Derived : public Base{
...
}
这个派生类是否总是调用基类的默认构造函数?即不带参数的构造函数?例如,如果我为基类定义一个构造函数:
Base(int newValue);
但我没有定义默认构造函数(无参数构造函数):
Base();
(我承认这只是一个声明,而不是一个定义)我收到一个错误,直到我定义不带参数的默认构造函数。这是因为基类的默认构造函数是由派生类调用的构造函数吗?
是的,默认情况下,调用默认构造函数。您可以通过显式调用非默认构造函数来解决此问题:
class Derived : public Base{
Derived() : Base(5) {}
};
这将调用采用参数的基构造函数,并且您不再需要在基类中声明默认构造函数。
调用默认构造函数的原因是,如果您创建了任何对象并且在该实例中没有传递参数(您可能希望稍后在程序中初始化它们)。这是最常见的情况,这就是为什么调用默认构造函数是必要的。
默认情况下,编译器提供三个默认值:
-
默认(无参数)CTOR
-
复制克托尔
-
赋值运算符
如果您自己提供了参数化的 Ctor 或复制 Ctor,那么编译器不会给出默认 Ctor,因此您必须明确编写默认 Ctor。
当我们创建一个派生类对象时,默认情况下它会搜索 Base 的默认 Ctor,如果我们没有提供它,那么编译器会抛出错误。但是,我们可以使派生类 Ctor 调用我们指定的基本 Ctor。
class Base {
public:
Base(int x){}
};
class Derived {
public:
Derived():Base(5){} //this will call Parameterized Base Ctor
Derived(int x):Base(x){} //this will call Parameterized Base Ctor
}
是的,默认情况下,调用默认构造函数。但是,如果您的基类具有参数化的构造函数,则可以通过两种方式调用非默认构造函数:
option 1: by explicitly calling a non-default constructor:
class Derived : public Base{
Derived() : Base(5) {}
};
选项 2:
in base class constructor set the parameter default value to 0, so it will
act as default as well as paramterized constructor both
for example:
class base
{ public:
base(int m_a =0){}
};
class Derived
{ public:
Derived(){}
};
上述方法适用于参数化构造函数调用和默认构造函数调用。
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 调用派生类成员函数
- 从 c++ 中派生类的析构函数调用虚函数
- 从基类 (C++) 调用派生类中的非虚函数
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何从 Gtk::窗口调用派生对象的析构函数
- 在dynamic_pointer_cast后调用派生类的构造函数
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 有没有办法在没有虚拟的情况下使用基类指针调用派生类函数
- C++:编译对无关派生类、bug或特性的函数调用
- C++通过 const 引用传递时不调用派生类函数
- 如何从包含基类指针的容器中调用派生类函数(基于其类型)?
- 从多重继承中的派生类函数调用适当的父类函数
- 从基类数组调用派生函数
- 从基类析构函数调用派生类方法
- 从基类函数调用派生类函数
- 从基类构造函数调用派生类的方法
- 从基类构造函数调用派生类的虚拟函数
- 从虚拟函数调用派生类的成员
- 如何从基类构造函数调用派生类虚拟方法