upcasting to interface with private inheritance

57 Views Asked by At

I have the following situation

class Interface {
};

class ComplicatedObject : public Interface {
};

and I would like to give a simplified version of the ComplicatedObject, still providing the Interface. I was thinking to private inheritance, such as

class Simplified : private ComplicatedObject {
};

but, of course, I can't easily upcast to Interface like

int main() {
  Interface* p = new Simplified();
}

Is composition the only way to go? or is there some workaround? like implicit conversion

1

There are 1 best solutions below

1
eerorika On

Is composition the only way to go?

Upcasting won't work with composition either. Private inheritance is effectively composition from the perspective of outside the class.

or is there some workaround?

Not implicit, but you could provide a set of member functions that return a reference to the base.


A more radical change - but more sensible - is to change the premise and use virtual inheritance:

class Interface {};

class ComplicatedObject : public virtual Interface {};

class Simplified : private ComplicatedObject, public virtual Interface {};

This can be done without virutal inhertance as well, but in that case you would need to re-implement all virtual functions and delegate to the private base explicitly.