I have the following scenario:
struct A { void f(); };
struct B : A { void g(); };
struct Base {
A &ref;
Base(A &a) : ref(a) {}
void f() { ref.f(); }
};
struct Derived : Base {
Derived(B &b) : Base(b) {}
// ERROR: ref does not have function g() since its stored as an A& in Base
void h() { ref.g() }
};
My question is how I can best represent what I'm trying to represent without making an extra duplicate reference. For example, one proposed solution is to add a member B& ref2
in Derived
but that would mean that we are storing an extra A&
in Base
since the new member has all the functionality of ref
.
Another solution I thought of is to change A& ref
to A* ptr
in Base
and use static_cast<B*>(ptr)
in Derived
. However, this feels fragile because in the future someone might change the constructor of Derived
to have an argument that is not a B
Is there a better solution? I have the ability to modify all classes in my scenario, so I have all the flexibility needed.