virtual inheritance question

C

chrolson

For the following classes, why is the output 1 instead of 10?:

class Top
{
public:
Top():a(1){}
Top(int arg):a(arg){}
virtual ~Top(){}
int a;
};

class Left : virtual public Top
{
public:
Left():b(2){}
int b;
};

class Right : virtual public Top
{
public:
Right(): c(3), Top(10){}
int c;
};

class Bottom : public Left, public Right
{
public:
Bottom():d(4){}
int d;
};

int main()
{
Bottom* bottom = new Bottom();
Right *right = bottom;
cout << "right->a: " << right->a << endl;

return 0;
}
 
J

John Grabner

For the following classes, why is the output 1 instead of 10?: ....


class Right : virtual public Top
{
public:
Right(): c(3), Top(10){}
int c;
};

class Bottom : public Left, public Right
{
public:
Bottom():d(4){}
int d;
};

int main()
{
Bottom* bottom = new Bottom();
Right *right = bottom;
cout << "right->a: " << right->a << endl;

return 0;
}

The virtual base class constructor must be called
from the most derived constructor. In this case it must
be called from Bottom.

John.
 
P

pauldepstein

John said:
The virtual base class constructor must be called
from the most derived constructor. In this case it must
be called from Bottom.

John.

I know this is a bit of a digression from the OP's question but
shouldn't there be a delete Bottom; to avoid a memory leak? (I'm not
completely sure -- this is a genuine question, not a rhetorical one.)

Paul Epstein
 
T

Todd Gardner

I know this is a bit of a digression from the OP's question but
shouldn't there be a delete Bottom; to avoid a memory leak? (I'm not
completely sure -- this is a genuine question, not a rhetorical one.)

Paul Epstein

In my opinion, yes and no. Yes, the memory needs to be deleted, but no,
not by delete. Here would be my main:

int main()
{
boost::shared_ptr<Right> right(boost::shared_ptr<Bottom>(new
Bottom()));
cout << "right->a: " << right->a << endl;

return 0;
}

The shared_ptr cleans up for you when it goes out of scope.

Todd Gardner
 
C

chrolson

The virtual base class constructor must be called
from the most derived constructor. In this case it must
be called from Bottom.

John.

So what happens to the explicit call to Top(10) in the initializer list
of class Right? Does it get called at all?
 

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

No members online now.

Forum statistics

Threads
474,299
Messages
2,571,544
Members
48,295
Latest member
Adriene271

Latest Threads

Top