Protected Constructor in multilevel virtual inheritance in C++

522 views Asked by At

How is the folloing code working? MakeFinal constructor is protected, so it should not be accessible to FinalUser class. But I didn't get any build or execution error.

class MakeFinal
{
protected:
    MakeFinal(void) {};

public:
    ~MakeFinal(void) {};
};

class Final : virtual public MakeFinal
{
public:
    Final(void) {};
    ~Final(void) {};
};

class FinalUser : public Final
{
public:
    FinalUser(void) {};
    ~FinalUser(void) {};
};

int main()
{
    FinalUser *finalUserHeap_ = new FinalUser();
    return 0;
}
3

There are 3 answers

0
Bo Persson On

Derived classes have access to protected members of their base classes. That's the difference between protected and private.

0
chema989 On

You need to know the next:

If the inheritance is public, everything that is aware of Base and Child is also aware that Child inherits from Base.

If the inheritance is protected, only Child, and its children, are aware that they inherit from Base.

If the inheritance is private, no one other than Child is aware of the inheritance.

@Anzurio answer in Difference between private, public, and protected inheritance

According this. You need to use private if you want that FinalUser class donot have access to MakeFinal.

6
Cheers and hth. - Alf On

A virtual base class is initialized by the single most derived class' constructor's member initializer list.

Because the virtual base can be a common base-class object for multiple derived classes, and the initializations specified by those derived classes can conflict.

The initialization specification in the most derived class acts conceptually as if the most derived class was derived directly from the virtual base class, i.e.

FinalUser(void) {};

… is equivalent to

FinalUser(): MakeFinal() {}

Since the MakeFinal constructor is protected, it's available to all derived classes.

That includes that it's available to class FinalUser.


In other news:

The names in this code indicate that it's about using a C++03 trick for creating a class that can't be (usefully) derived from, a “final” class. The trick is essentially to have a class template that can act as most derived class and that has the necessary friend-ship to access the for other classes inaccessible constructor of the virtual base class. C++11 introduced the keyword final to do that more easily, and without the overhead of virtual inheritance.