I'm having trouble with C++ classes and inheritance right now...
Let's say we have
Class A {
A(string name);
~A();
void func(void);
}
Class B : public A {
B(string name);
~B();
...
}
Class C : public A {
C(string name);
~C();
...
}
Class D : public B, public D {
D(string name);
~D();
...
}
Whenever I create D, it calls the constructor for B and the one for C which results in multiple instances of A. The compiler then says it doesn't know which "func" it should call, the one from B or the one from C.
I would like to know how to call A constructor ONLY ONCE and then use it to build B and C.
I already tried using B::func() to be able to call func() but has I must have a cout in the class A builder. It results in wrong output.
This is called the diamond inheritance pattern.
In order to avoid having 2 instances of
AinD, you need to use virtual inheritance.When classes e.g.
Bvirtually inheritA, it means thatAwill be present only once in a class derived from those classes.Note: in this case it is the responsibility of the most derived class to initialize the virtual base(s) - as shown below.
The output from the following code demonstrates it:
Output:
I.e.
Ais present once inD.Note that if you remove the
virtualkeyword, the output will be:I.e.
Ais present twice inD(as you observed).Some side notes:
using namespace std- see here Why is "using namespace std;" considered bad practice?.Classshould beclass, missing;at the end of classes.namebyconst &as demonstrated in my code, to avoid copy.