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
    }
}

Refer to the code snippet below:

Child* c = dynamic_cast<Child*>(parentObject);

where, parentObject is of type Parent*

Ensure, that the "parentObject" is actually of "Child" type, otherwise undefined-behavior.

Refer for More Info

Tags:

C++