为什么为派生类定义复制构造函数需要基类的默认构造函数已定义?

huangapple go评论74阅读模式
英文:

Why does defining a copy constructor for derived class requires that the default constructor for base class be defined?

问题

我在单个cpp文件中有以下代码:

class Base
{
  public:
    //constructor
    Base() = delete;
};

class Derived : public Base
{
  public:
    //copy constructor
    Derived( const Derived & other ){};
};

int main( int argc, char* argv[] )
{
  //empty
}

然而,编译cpp文件会导致错误:

exp.cpp: 在复制构造函数‘Derived::Derived(const Derived&)’中:
exp.cpp:15:37: 错误:使用已删除的函数‘Base::Base()’
     Derived( const Derived & other ){};
                                     ^
exp.cpp:7:5: 注意:在此声明
     Base() = delete;
     ^~~~

我不明白为什么会出错。在定义派生类的复制构造函数时,基类的默认构造函数是如何起作用的?

英文:

I have the following code in a single cpp file:

class Base
{
  public:
    //constructor
    Base() = delete;
};

class Derived : public Base
{
  public:
    //copy constructor
    Derived( const Derived & other ){};
};

int main( int argc, char* argv[] )
{
  //empty
}

However, compiling the cpp file results in an error

> exp.cpp: In copy constructor ‘Derived::Derived(const Derived&)’:<br>
> exp.cpp:15:37: error: use of deleted function ‘Base::Base()’<br>
> Derived( const Derived & other ){};<br><br>
> exp.cpp:7:5: note: declared here<br>
> Base() = delete;<br>
> ^~~~<br>

I don't understand why. How does the base class default constructor come into play when you define the copy constructor for derived class?

答案1

得分: 6

构造派生类对象需要构造其基类对象(因为派生实例是基实例+扩展)。

因此,初始化派生实例需要初始化基实例。问题是,当我调用派生类的构造函数时,哪个基类的构造函数被调用?因为您定义了派生构造函数如下:

Derived( const Derived & other ){};

编译器注意到您没有指定调用特定的基类构造函数,因此它生成了一个不带参数的构造函数的调用。但是,遗憾的是,您已经从基类中删除了这个构造函数。因此,它会产生一个错误。

您可能会认为调用派生类的复制构造函数会生成对未删除的基类的复制构造函数的调用。但是,不幸的是,规则是如果您不为基类指定特定的构造函数调用,那么将调用不带参数的构造函数。

英文:

Constructing an object of derived class necessitate to construct an object of its base class (as a derived instance is a base instance + extension).

Thus initializing the derived instance necessitate to initialize the base instance. The question is then when I call a ctor for the derived class, which ctor of the base class is called? As you defined the derived ctor as:

Derived( const Derived &amp; other ){};

the compiler observed that you didn't specified a call to a specific base class ctor, it then generates a call to the ctor with no parameter. But, alas, you deleted it from the base class. It then emits an error.

You may think that calling a copy ctor for the derived class will generates a call to the copy ctor of the base class which wasn't deleted. But, alas, no, the rule is that if you don't specify a specific ctor call for the base class, the ctor with no parameter is called.

huangapple
  • 本文由 发表于 2020年1月6日 16:35:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608913.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定