Reputation: 113
I tried splitting a data structure into several base classes to reuse the code and data members. There i encountered the issue that it would greatly simplify my code if i could initialize the members of one base class with the members of another.
struct Base1
{
const int a;
Base1() : a(3) {}
};
struct Base2
{
const int b;
Base2() : b(a*2) {}
};
struct Derived :
Base1,
Base2
{
Derived() : Base1(), Base2() {}
};
Since the above is not possible, I'm searching for a way to achieve something similar, with changing the class Base1 and Base2 as little as possible. How could I do that?
Upvotes: 0
Views: 44
Reputation: 2914
You'll need a clean interface. As Base2
is not related to Base1
in any way per your example, the dependency you describe shall be part of it's interface to the outward world. It is not an implementation detail.
As such the correct solution would be to provide an explicit (i don't mean the keyword) constructor:
Base2(int a) : b(a*2) {}
For Derived
you then get:
Derived() : Base1(), Base2(a) {}
Notice that Base1
gets initialized before Base2
and as such a
is already available.
Upvotes: 2