How do I cast a parent class as the child class

A Parent object returned by value cannot possibly contain any Child information. You have to work with pointers, preferably smart pointers, so you don’t have to clean up after yourself:

#include <memory>

class Factory
{
    // ...

public:

    static std::unique_ptr<Parent> GetThing()
    {
        return std::make_unique<Child>();
    }
};

int main()
{
    std::unique_ptr<Parent> p = Factory::GetThing();
    if (Child* c = dynamic_cast<Child*>(p.get()))
    {
        // do Child specific stuff
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)