On 2013-02-28 09:02, omveer wrote:
> Hi,
>
> I'm trying below scenario:
> class xx
> {
> xx(){}
> friend class yy;
> };
>
> class yy: virtual public xx
> {
> public:
> yy(){}
> };
>
> class zz:public yy
> {
> public:
> };
>
> Q1: It doesn't work with ZZ obj; Please help me understanding it.
In the future please always explain what you mean with "it doesn't
work". This description can mean anything or everything and I usually
don't reply to such fuzzy questions. I'm assuming in the following
that your problem is a compiler error when attempting to compile an
object declaration of the form
zz obj;
complaining along the lines of "default constructor of xx is not
accessible" or something similar.
In this case, both your questions are *related*. Virtual base classes
are very special, because they are initialized at a different time
compared to the normal way (C++ base classes and non-static members
are otherwise always initialized *before* the container class): They
are always initialized *first* by the most-derived class. This causes
a problem in your example, because it is *not* yy who is supposed to
invoke the (private) xx default constructor for an object of type zz,
but it is the type zz. Since you did not assign access rights to zz,
the implicit invocation is invalid.
A simple fix is to assign friendship to zz as well. Personally I would
stay away from such a design (virtual base class with private default
constructor), because it doesn't scale well: Your virtual base class
has to be aware of all derived classes - gulp! If you want to prevent
that user-code directly declares an object of type xx, you could
simply make the default constructor protected instead.
> class xx
> {
> xx(){}
> friend class yy;
> };
>
> class yy: public xx
> {
> public:
> yy(){}
> };
>
> class zz:public yy
> {
> public:
> };
>
> Q2: After removing virtual, it works for zz obj;. Why and how?
My description above explains it: In this case we have no virtual base
class, so yy is the type that will construct the xx base class. Thus,
the friendship to yy will ensure that this construction is valid.
HTH & Greetings from Bremen,
Daniel Kr�gler