GAME ENGINE : dynamic_cast - Object class is not a polymorphic type

295 Views Asked by At

First of all im trying to create a games engine with similar architecture to Unity. I have an Object class, a GameObject class which inherits from Object. Within GameObject class i am trying to make a template class that will let you add any component onto the game object, although i get a dynamic pointer cast error which i cant seem to solve.

Heres the GameObject class:

class GameObject : public Object 

{

public:

template<class T>
std::shared_ptr<T> addChildComponent()
{
    std::shared_ptr<T> temp_component(new T());

    temp_component->gameObject = std::dynamic_pointer_cast<GameObject>(shared_from_this());
    m_components.push_back(temp_component);

    return temp_component;
}

template<class T>
std::shared_ptr<T> getComponent()
{
    for (int i = 0; i < m_components.size(); i++)
    {
        std::shared_ptr<T> t;
        t = m_components.at(i);

        if (t.get() != NULL)
        {
            return t;
        }
    }

    return std::shared_ptr<T>();

}

Furthermore this is the Object Class which it inherits from:

class Object : public std::enable_shared_from_this<Object>
{

friend class GameObject;

public:
Object();
~Object();


void makeName(std::string _name);

std::string getName();

private:
std::string name;


};
1

There are 1 best solutions below

0
On BEST ANSWER

The error means that whatever you are trying to cast from does not have any virtual members. A base class of a virtual inheritance chain should always have a virtual destructor at minimum and then you would no longer get this error.

As an example, the following would exhibit the error you have:

class base1
{
int a;
};
class derived1: public base1
{};
...
derived1 d1;
base1 * pb1 =&d1;
derived1 * pd1 = dynamic_cast<derived1*>(pb1);

While the next would not:

class base2
{
int a;
public:
virtual ~base1() {}
};
class derived2 : public base2
{};
...
derived2 d2;
base2 * pb2 = &d2;
derived2 * pd2 = dynamic_cast<derived2*>(pb2);