派生类构造函数调用

时间:2012-11-19 00:35:09

标签: c++ inheritance constructor derived-class base-class

如果我有基类:

class Base{
  ...
};

和派生类

class Derived : public Base{
  ...
}

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

Base(int newValue);

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

Base();

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

4 个答案:

答案 0 :(得分:9)

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

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

默认编译器提供三个默认值:

  1. 默认(无参数)Ctor

  2. 复制Ctor

  3. 作业运算符

  4. 如果您自己提供参数化Ctor或Copy Ctor,则编译器不会提供默认Ctor,因此您必须明确写入Default Ctor。

    当我们创建Derived类对象时,它默认搜索Base的默认Ctor,如果我们没有提供它,那么编译器会抛出错误。但是我们可以使Derived类Ctor调用我们指定的Base 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
    }
    

答案 3 :(得分:0)

是的,默认情况下,会调用默认构造函数。但是如果您的基类具有参数化的构造函数,那么您可以通过两种方式调用非默认构造函数。:

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(){}
};

上述方法对于参数化构造函数调用和默认构造函数调用都可以正常工作。