I have a couple of classes one of which keeps reference to the object of other:
class Inner {};
class Outer {
Inner & in;
public:
Outer(Inner & in) : in(in) {}
};
What if I have to create Outer object from const reference to Inner? Am I have to write specific class, say OuterConst, for this?
UPD: Any neat solutions using templates? In order to avoid duplication of code in OuterConst class.
UPD2: when Inner comes without const it should be modifiable (so I can’t just add const to Inner member in current implementation of Outer).
You could store a const reference, and use
const_castto cast the const away when needed. If you add some runtime checking, it’s also safe.And of course you can always split this into two classes: one that cannot change
in, and another that can.To do this, you could either derive the class that can change
infrom the class that cannot. Or you could derive both from a common base class which has the common functions as protected members, and make the appropriate ones public withusing Base::Functionin the derived classes.