Naruto
Naruto

Reputation: 9634

Virtual base class object creation

I have question related to virtual base class.

class a
{
public:
  a();
  ~a();
};

class b: virtual public a
{
public:
  b();
  ~b();
};

class c: virtual public a
{
public:
  c();
  ~c();
};

class e: public b, c
{
public:
  e();
  ~e();
};

Whenever I create an object of class e, via which class the a object will be created in e?

Upvotes: 0

Views: 115

Answers (2)

Science_Fiction
Science_Fiction

Reputation: 3433

A single shared instance will be present.

Compiler will give both class B and C a vpointer since the memory offset to A is unknown until runtime. When you create instance of E, it will also create an instance of A, B and C.

Both B and C contain a virtual pointer in their vtable that stores an offset to class A, this will be used at runtime to point to the shared A object.

Upvotes: 1

AProgrammer
AProgrammer

Reputation: 52294

Both, it will be shared.

If your question is about the layout, this is unspecified. Yes with virtual inheritance in place, an object -- when it isn't a complete object -- may be non-continuous in memory.

If a hasn't a default constructor, you need an initialization list in e which will provide the needed parameters; those implied by the constructors of b and c will be ignored.

Upvotes: 2

Related Questions