Smart pointers and polymorphism
I have applied reference counting pointers (called SP
in the example) and I am having problems with polymorphism, which I think it shouldn't be.
In the following code:
SP<BaseClass> foo()
{
// Some logic...
SP<DerivedClass> retPtr = new DerivedClass();
return retPtr;
}
DerivedClass
inherited from BaseClass
. With normal pointers, this should have worked, but with smart pointers, it speaks "cannot convert from 'SP<T>' to 'const SP<T>&"
and I think it refers to the smart pointer copy constructor.
How to resolve this kind of polymorphism with reference counting pointer? I would appreciate some code examples because obviously I am doing something wrong here if I am having this problem.
PS: Please don't tell me to use the standard library with smart pointers because that is not possible at the moment.
a source to share
In addition to the copy constructor:
SP(const SP<T>& ref);
you need a conversion constructor:
template<typename T2>
SP(const SP<T2>& ref);
Otherwise, the compiler doesn't know how to build SP<BaseClass>
from SP<DerivedClass>
; for him they are not related.
The conversion constructor is pretty trivial, as inside you can automatically convert *DerivedClass
to *BaseClass
. The code can be very similar to the code for the copy constructor.
a source to share