c++constructor

virtual base class with public/private constructor Behavior difference


if i run this code

#include<iostream>
using namespace std;
class Final;

class MakeFinal{
public:
friend class Final;
MakeFinal(){cout<<"makefinal\n";}
};

class Final: public virtual MakeFinal{
public:
 Final(){cout<<"Final\n";}
};

 class Derived:public Final{
public:
  Derived(){cout<<"Derived\n";}
};


int main(){
//Final f;
Derived d;
return 0;
}

Output is :

makefinal Final Derived

But if i make MakeFinal() constructor private , compiler shows error message. What is this different constructor call hierarchy based on ?


Solution

  • Refer to:

    C++ FAQs - virtual inheritance constructors http://www.parashift.com/c++-faq/virtual-inheritance-ctors.html

    Because of the fact that "Initialization list of most-derived-class's ctor directly invokes the virtual base class's ctor. ", your most derived needs to invoke the constructor of the virtual base directly. Therefore, for what you want to do you'd need to make the most derived class a friend too...

    Furthermore, it seems that you don't understand virtual inheritance correctly. Refer to this FAQ to understand the purpose and proper use of virtual inheritance.