ThefrenchSpeedruns
ThefrenchSpeedruns

Reputation: 113

Returning pointer to inherited class C++

I have a base-class (node) which gets inherited by node2D, which gets inherited by CSprite2D (I am working on a game-engine)

I have a vector of pointers to my objects inherited from NODE.

In my function CNode* getNodeByName(QString name) I return a CNode, but I can't do

CSprite2D* sprite = getNodeByName("hello")

Why is that and what could be a workaround? I already tried it returning a CSprite2D and it worked like a charm. I already tried to declare my function as virtual CNode* getNodeByName(Qstring name)

PS: I am using Qt if that matters. And also, I'm new to C++ so I it possible I oversaw something.

Upvotes: 0

Views: 91

Answers (1)

Venom
Venom

Reputation: 1060

if CSprite2D inherits CNode (in you question you said node) you can do the following :

CSprite2D* sprite = static_cast< CSprite2D* >(getNodeByName("hello"));

only if you are sure that the object returned is a CSprite2D*, otherwise it is undefined behavior.

You can also use dynamic_cast (see example in the link), dynamic_cast wwill return a null pointer or if the cast fails.

CSprite2D* sprite = dynamic_cast< CSprite2D* >(getNodeByName("hello"));

Upvotes: 1

Related Questions