派生类构造函数调用

Derived Class Constructor Calls

本文关键字:函数调用 派生      更新时间:2023-10-16

如果我有一个基类:

class Base{
  ...
};

和派生类

class Derived : public Base{
  ...
}

这个派生类是否总是调用基类的默认构造函数?即不带参数的构造函数?例如,如果我为基类定义一个构造函数:

Base(int newValue);

但我没有定义默认构造函数(无参数构造函数):

Base();

(我承认这只是一个声明,而不是一个定义)我收到一个错误,直到我定义不带参数的默认构造函数。这是因为基类的默认构造函数是由派生类调用的构造函数吗?

是的,默认情况下,调用默认构造函数。您可以通过显式调用非默认构造函数来解决此问题:

class Derived : public Base{
    Derived() : Base(5) {}
};

这将调用采用参数的基构造函数,并且您不再需要在基类中声明默认构造函数。

调用默认构造函数的原因是,如果您创建了任何对象并且在该实例中没有传递参数(您可能希望稍后在程序中初始化它们)。这是最常见的情况,这就是为什么调用默认构造函数是必要的。

默认情况下,编译器提供三个默认值:

  1. 默认(无参数)CTOR

  2. 复制克托尔

  3. 赋值运算符

如果您自己提供了参数化的 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(){}
};

上述方法适用于参数化构造函数调用和默认构造函数调用。