简体   繁体   中英

How does a class instance get constructed when inheriting a constructor from a base class?

Say I have this code:

#include <string>
using namespace std::literals;

struct A {
    A(std::string) { };
};

struct B : A {  };

And then construct objects like this:

A a("foo");
B b("foo"s);    // fails in clang
B c(A("foo"));  // fails in clang
B d("foo");     // fails in clang + gcc
B e({"foo"});   // fails in clang

A f{"foo"};
B g{"foo"s};
B h{A{"foo"}};
B i{"foo"};     // fails in clang + gcc
B j{{"foo"}};

How are a , b , c , ... actually constructed? What conversion, initialization method, constructor actually gets called? And why does it fail?

cigien pointed out that B doesn't automatically inherit any constructor from A and is an aggregate type. So aggregate initialization happens for B . And aggregate initialization with () is a c++20 feature that clang does not yet support. That explains all the differences between gcc and clang.

  • a and f do an implicit conversion from const char * to std::string before calling A(std::string) .

  • b and g call A(std::string) during aggregate initialization

  • c and h call A(const A&) during aggregate initialization

  • d and i fail to find a const char * -> A conversion for aggregate initialization

  • e and h call A(const std::initializer_list &) which in turn uses A(std::string) to initialize the B::A

d and i bugs me. Feels inconsistent. If I can construct A from const char * then why not there? But that's C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM