Reputation: 11733
i have 2 class: hObject, Drawer. Drawer inherit from hObject.
with this code i retrive a particular object by id:
hObject * foundObj = hManager::getInstance()->getObject("drawer_id");
now i want to correctly cast foundObj from hObject to Drawer. with:
vector<int> points = ((DrawerWidget *)hObject)->getPoints();
i recive
expected primary-expression before ‘)’ token
and what about dynamic cast?
consideration: my skills has been halved till i began c++
Upvotes: 0
Views: 1822
Reputation: 254461
Two problems:
hObject
(the type name) when you meant foundObj
(the object name)Fixing that, and also using a less dangerous C++-style cast, the following should work:
vector<int> points = (static_cast<DrawerWidget*>(foundObj))->getPoints();
and what about dynamic cast?
If the base class is polymorphic (that is, has at least one virtual function), then that would be safer still - you can check at runtime that the cast is valid:
if (DrawerWidget * dw = dynamic_cast<DrawerWidget*>(foundObj)) {
vector<int> points = dw->getPoints();
} else {
// not a DrawerWidget
}
although if you find yourself doing that, I would have a think about the design: it might be more appropriate to redesign the base class to support what you want to do via virtual functions, or to ensure at compile time that the conversion is valid.
Upvotes: 3
Reputation: 385144
You accidentally wrote the pointer's type, not name:
vector<int> points = ((DrawerWidget *)hObject)->getPoints();
// ^^^^^^^
You meant:
vector<int> points = ((DrawerWidget *)foundObj)->getPoints();
// ^^^^^^^^
Also, for great victory, prefer C++-style casts:
vector<int> points = (static_cast<DrawerWidget*>(foundObj))->getPoints();
Finally, if it's possible that *foundObj
isn't actually a DrawerWidget
, and if these types are polymorphic, consider not casting and relying on virtual dispatch instead.
Upvotes: 3