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
?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.