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
Could anybody explain me this code?
EDIT: Also another question i have is what is a virtual derivation and when is it needed?
It’s a property of
virtualderivation.The idea of
virtualderivation is to solve the “Dreaded Diamond Pattern”:The problem here is that
TopDiamondhas 2 instance ofBasehere.To solve this problem, very peculiar “MultiInheritance”, C++ uses the
virtualkeyword and what is thus called “virtual inheritance”.If we change the way
D1andD2are defined such that:Then there will only be one instance of
BasewithinTopDiamond: the job of actually instantiating it is left to the top-constructor (hereTopDiamond).Thus, the little trick you have shown is simply explained here:
Usablederives virtually fromUsable_lock, it’s up to its derived class to instantiate theUsable_lockpart of the objectUsable_lockconstructor isprivate, only itself andUsable(friend) can access the constructorIt’s clever, I had never thought of that. I wonder what the cost of
virtualinheritance is here (extra memory / speed overhead) ?