A class that cannot be inferred

I found this code here

class Usable; class Usable_lock { friend class Usable; private: Usable_lock() {} Usable_lock(const Usable_lock&) {} }; class Usable : public virtual Usable_lock { // ... public: Usable(); Usable(char*); // ... }; Usable a; class DD : public Usable { }; DD dd; // error: DD::DD() cannot access // Usable_lock::Usable_lock(): private member 

Can someone explain this code to me?

EDIT . Another question I have is what is virtual derivation and when is it needed?

+4
source share
3 answers

This is a virtual output property.

The idea behind virtual output is to solve the Scary Diamond Pattern:

 struct Base {}; struct D1: Base {}; struct D2: Base {}; struct TopDiamond: D1, D2 {}; 

The problem here is that TopDiamond has 2 Base instances here.

To solve this problem, a very peculiar "MultiInheritance", C ++ uses the virtual and what is called the so-called "virtual inheritance".

If we change the way D1 and D2 , we define such that:

 struct D1: virtual Base {}; struct D2: virtual Base {}; 

Then TopDiamond will be only one Base instance in TopDiamond : the task of its actual instance remains in the upper constructor (here TopDiamond ).

So the little trick you showed is simply explained here:

  • because Usable obtained practically from Usable_lock , it creates an instance of the Usable_lock part of the object before its derived class
  • Since the constructor is Usable_lock private , only Usable (friend) can access the constructor

This is smart, I never thought about it. I wonder what is the virtual inheritance cost here (extra memory / overhead speed)?

+5
source

class Usable_lock The constructor is declared under Private. Thus, it is not accessible from the outside.

 Usable_lock class 

when you create an object

  DD dd; 

It will call the constructor of Usable and Usable_lock both (because DD derived from Usable and Usable Usable_lock produced from Usable_lock )

and therefore it cannot access the Usable_Lock Constructor .. and it will give you an error

+1
source

There are two points here:

1) Why can a useful instance be created, although it includes a private constructor, Usable_lock? Because Usable is a friend of Usable_lock.

2) Why can't I create an instance based on usage? Since it includes the private constructor Usable_lock.

+1
source

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


All Articles