Lets say I have an abstract base class with a pure virtual that returns an expensive object. As it’s an expensive object, I should return a reference to it.
But life’s not that simple, let’s say I have two classes derived from it: one has the function called often, so it is more efficient to store a copy in the instance and return a reference. The other is called rarely, so it is better to create the object on demand to save RAM.
I thought I could just use covariance because the Liskov substitution principle would be happy, but of course Obj is not a subtype of Obj&, so compile errors result.
class abc
{
public:
virtual BigObj& obj() = 0;
};
class derived : public abc
{
public:
...
virtual BigObj obj() { return obj_; }
private:
BigObj obj_;
};
Results in:
conflicting return type specified for ‘virtual BigObj derived::obj()’
Is there a more elegant solution to this than simply picking the least worst?
One solution is to create a smart pointer class to manage
BigObj*s:Then change your classes to return one of these, and set the
delbool to whether you want theBigObjPtrto destroy its pointer when it goes out of scope:You’d of course need to manage copying of
BigObjPtrs, etc. but I leave that to you.