Search code examples
c++inheritancememorycastingprivate-constructor

How to downcast properly in C++


For any reason, I have an object created by a static method which calls the private constructor. (It isn't a singleton)

I want to make a new object derives from the first one, which have more members and functions.
But it's problematic, becuase the static method returns a firstObject* object, so a creation with downcasting of the secondObject* will make a memory overflow.

What should I do? I have an access to the first object's code, but it is impossible to change its constructor (If I change it, I will have to change a huge written code).

EDIT:

Thank to all responders. I can change the constructor to be protected.


Solution

  • Make sure your constructor is at least protected so that child classes can use it.

    Not sure what you fear about memory overflow but this:

    class Base {
    public:
      static Base* getInstance();
      virtual ~Base() {};
    protected:
      Base() {};
    };
    
    class Derived : public Base {};
    
    // Implementation
    Base* Base::getInstance() { return new Derived(); }
    
    int main() {
    Base::getInstance();
    };
    

    Works perfectly.

    Now I would advise you against returning a raw pointer in that situation (std::unique_ptr would be way better) but that's probably off-topic.