By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,804 Members | 1,634 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,804 IT Pros & Developers. It's quick & easy.

Whats the deal with virtual inheritance

P: n/a
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
Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a


Amol Chavan wrote:

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

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.