D
D
Dead_Bit2019-10-26 16:37:09
OOP
Dead_Bit, 2019-10-26 16:37:09

Multiple call to base class constructor with virtual inheritance?

There is the following code:

class A {
private: int a;
public: A(int a) : a(a) {}
};
class B : public virtual A {
private: void* b;
public: B(int a) : A(a) { b = malloc(8); }
};
class C : public virtual A {
private: void* c;
public: C(int a) : A(a) { c = malloc(16); }
};
class D : public C {
private: void* d;
public: D(int a) : C(a) { d = malloc(32); }
};

In the constructor of class D, the following error occurs: "there is no default constructor for class A".
If you add a call to constructor A to constructor D, then the error disappears, but the question arises: "Will the base class constructor A be called twice, because constructor A is also called in constructor C?".
class D : public C {
private: void* d;
public: D(int a) : A(a), C(a) { d = malloc(32); }
};

Thanks in advance for your reply.
PS I need such a hierarchy of classes, since some classes are inherited from B or C separately, while others inherit both classes at once. Class D is just an example of one such class.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2019-10-27
@Dead_Bit

this begs the question "Will the base class constructor A be called twice, because constructor A is also called in constructor C?".

No, it won't, because no, when constructing an object of class D, constructor A is not called from constructor C. See :
A mem-initializer where the mem-initializer-id denotes a virtual base class is ignored during execution of a constructor of any class that is not the most derived class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question