Why “an inherited constructor is not a candidate for initialization from an expression of the same or derived type”?

亡梦爱人 提交于 2019-12-10 18:29:16

问题


I expected this to work

struct Parent
{
    Parent ();

    Parent (const Parent &);
};

struct Child : public Parent
{
    using Parent::Parent;
};

Parent p;

Child c (p);

Child inherits all of Parent's constructors, right?

Including Parent::Parent(const Parent &)?

x.cpp:15:11: error: no matching function for call to ‘Child::Child(Parent&)’
 Child c (p);
           ^
x.cpp:5:2: note: candidate: Parent::Parent(const Parent&)
  Parent (const Parent &);
  ^~~~~~
x.cpp:10:16: note:   inherited here
  using Parent::Parent;
                ^~~~~~
x.cpp:10:16: note:   an inherited constructor is not a candidate for initialization from an expression of the same or derived type
x.cpp:8:8: note: candidate: Child::Child()
 struct Child : public Parent
        ^~~~~

Why can't I construct a Child from a Parent?


回答1:


Inheriting a constructor doesn't prevent the default copy constructor of Child from being generated by the compiler.

This implies that you have a Child::Child(const Child&) which is hiding the inherited constructor that can't be chosen by lookup resolution, as cppreference.com explains:

if an inherited constructor matches the signature of one of the constructors of Derived, it is hidden from lookup by the version found in Derived. If one of the inherited constructors of Base happens to have the signature that matches a copy/move constructor of the Derived, it does not prevent implicit generation of Derived copy/move constructor (which then hides the inherited version, similar to using operator=).

In §12.9 of C++11 ISO standard is it stated:

For each non-template constructor in the candidate set of inherited constructors other than a constructor having no parameters or a copy/move constructor having a single parameter, a constructor is implicitly declared with the same constructor characteristics unless there is a user-declared constructor with the same signature in the class where the using-declaration appears.



来源:https://stackoverflow.com/questions/57926023/why-an-inherited-constructor-is-not-a-candidate-for-initialization-from-an-expr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!