I am creating a custom shared pointer in C++ to learn how these things work.
My implementation is not general purpose, I only want it to be used with a class Foo or an any of its subclasses.
This is what my classes look like:
template <typename T>
class ReferenceCounter final
{
private:
T* m_Value;
unsigned int m_Counter;
};
template <typename T>
class SharedPtr final
{
private:
ReferenceCounter<T>* m_ReferenceCounter;
};
I have also implemented all the constructors, copy constructors, assignment operators, etc. I didn’t show them here because it is a lot of code and I don’t think it is relevant to the question.
Now I want to add two functionalities:
- I want to be able to implicitly convert a shared pointer from a subclass to a base class like this:
SharedPtr<Foo> f = MakeShared<FooDerived>();
- I want to be able to cast from a base class to a derived class, returning nullptr if the conversion is not possible:
SharedPtr<Foo> f = ...; SharedPtr<FooDerived> fd = TryCast<FooDerived>(f);
How can this be implemented?
Edit: minor text and title changes