Whats the deal with virtual inheritance

A

Amol Chavan

I was debating with my friend on how to make a class final as in java,
where it can't be further derived but instatiated. So I search the net
and found to do so. Make a base class which has constructor private.
And a Final class inheriting from it privately.
// Code snippet
class FinalBase
{
FinalBase() {}
friend class Final;
};

class Final : virtual private FinalBase
{
public:
};
class DerivedFinal : public Final
{

};

int main()
{
DerivedFinal df;
}

The above code does not compile and gives error in VC++ as follows
error C2248: 'FinalBase::FinalBase' : cannot access private member
declared in class 'FinalBase'.

If I remove the keyword virtual while inheriting from the FinalBase.
The code compiles without any error ... Any comments on this ???

-Amol
 
K

Karl Heinz Buchegger

Amol said:
I was debating with my friend on how to make a class final as in java,
where it can't be further derived but instatiated. So I search the net
and found to do so. Make a base class which has constructor private.
And a Final class inheriting from it privately.
// Code snippet
class FinalBase
{
FinalBase() {}
friend class Final;
};

class Final : virtual private FinalBase
{
public:
};
class DerivedFinal : public Final
{

};

int main()
{
DerivedFinal df;
}

The above code does not compile and gives error in VC++ as follows
error C2248: 'FinalBase::FinalBase' : cannot access private member
declared in class 'FinalBase'.

If I remove the keyword virtual while inheriting from the FinalBase.
The code compiles without any error ... Any comments on this ???

Yep. What is your question?
Why virtual derivation is crucial in the intent?

Well. If you derive virtual then the most derived class is responsible
for initializing the base class. So in this case DerivedFinal
is responsible for constructing FinalBase. But DerivedFinal can't
do so, because the ctor is private and DerivedFinal is not a friend
of FinalBase.
If you derive Final non-virtual then things change. The initialization
chain is: DerivedFinal has to initialize FinalBase and FinalBase has
to initialize Final. All of this is working, since Final is a friend
of FinalBase.

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top