How to call copy constructor of all base classes for copying most derived class object in diamond inheritance in C++?

前端 未结 4 1731
囚心锁ツ
囚心锁ツ 2021-02-15 23:31

Consider the below code:

#include
using namespace std;
class A
{
public:
     A() {cout << \"1\";}
     A(const A &obj) {cout <<          


        
4条回答
  •  梦谈多话
    2021-02-16 00:13

    Regarding access checking for constructors: from [class.access]/6

    All access controls in Clause [class.access] affect the ability to access a class member name from the declaration of a particular entity ... [ Note : This access also applies to implicit references to constructors, conversion functions, and destructors. — end note]

    similarly, [class.access]/4

    Special member functions obey the usual access rules. [ Example: Declaring a constructor protected ensures that only derived classes and friends can create objects using it. — end example ]

    Regarding base class subobject initialization: from [class.base.init]/9

    In a non-delegating constructor, if a given potentially constructed subobject is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer), then ... otherwise, the entity is default-initialized

    The lack of any ctor-initializer for a base class subobject means that the subobject is default-initialized; from [dcl.init]/7

    To default-initialize an object of type T means: ... The constructor thus selected is called, with an empty argument list, to initialize the object.

    So the lack of any base in a ctor-initializer is a request for default-initialization for that base, which means calling the default constructor.

    The lack of mention of a base class makes no difference; in any case, a constructor has no name and is not named in the ctor-initializer, it is referenced either explicitly or implicitly. There is nothing in the standard suggesting that access control should not be performed in such case.

    It seems like the constructor, being from an inaccessible base class, cannot be called either way, so your program should not compile.

    In any case, you can change the inheritance from private to protected, even add a path to the virtual base class:

    class D: B, C, virtual A
    {
    

    This way, the virtual base class A is still private, but is accessible to D.

提交回复
热议问题