How to call the copy constructor of all base classes to copy most class class objects to diamond inheritance in C ++?

Consider the code below:

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

class B: virtual A
{
public:
    B() {cout << "3";}
    B(const B & obj) {cout<< "4";}
};

class C: virtual A
{
public:
   C() {cout << "5";}
   C(const C & obj) {cout << "6";}
};

class D:B,C
{
public:
    D()  {cout << "7";}
    D(const D & obj) {cout << "8";}
};

int main()
{
   D d1;
   cout << "\n";
   D d(d1);
}

The output of the program is below:

1357
1358

So, for the string D d(d1), the class copy constructor Dis called. During inheritance, we need to explicitly call the constructor of the copy of the base class, otherwise only the default constructor of the base class will be called. I understood so far.

My problem:

Now I want to call the constructor of copying all base classes at runtime D d(d1). For this, if I try below, D(const D & obj) : A(obj), B(obj), C(obj) {cout << "8";} then I get this error: Error:'class A A::A' is inaccessible within this context

. , A, B C, D. , .

+4
4

-, , :

class B : virtual protected A {...};
class C : virtual protected A {...};

, , , A B C:

class D : protected B, protected C {
    D(const D & obj) : A(obj), B(obj), C(obj) {cout << "8";}
};

(2468).

?

, , , B C A.

ยง12.6.2, (13.1):

:

  • -, (1.8), , " " - - .

, , , .

+8

, private.

B A C A protected public, .

class B : protected virtual A
{
   ...
}

class C : protected virtual A
{
   ...
}

class B : public virtual A
{
   ...
}

class C : public virtual A
{
   ...
}

D copy:

D(const D & obj) : A(obj), B(obj), C(obj) {cout <<"8";}

PS , private.

+3

, B C:

class A
{
public:
     A() {cout << "1";}
     A(const A &obj) {cout << "2";}
};

class B: virtual A
{
public:
    B() {cout << "3";}
    B(const B & obj) {cout<< "4";}
};

class C: virtual A
{
public:
   C() {cout << "5";}
   C(const C & obj) {cout << "6";}
};

class D:B,C,virtual A
{
public:
    D() {cout << "7";}
    D(const D & obj) : A(obj), B(obj), C(obj) {cout << "8";}
};
0

: [class.access]/6

[class.access] ... [: , . - ]

[class.access]/4

- . [ : , , . - ]

: [class.base.init]/9

, mem-initializer-id ( mem-initializer-list, ctor-), ...

ctor- , ; [dcl.init]/7

T :... , .

, - ctor-initializer , .

; ctor-initializer, , . , , .

, , , , .

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

class D: B, C, virtual A
{

Thus, the virtual base class Aremains private, but is accessible to D.

0
source

Source: https://habr.com/ru/post/1676015/


All Articles