nkint
nkint

Reputation: 11733

Cast and : from parent to child class

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

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254461

Two problems:

  • you wrote hObject (the type name) when you meant foundObj (the object name)
  • it's a pointer, so you need to cast to a pointer type (UPDATE: the question has been edited to fix that).

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

Lightness Races in Orbit
Lightness Races in Orbit

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

Related Questions