简体   繁体   中英

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.

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM