Subj : Re: Typecasting question To : borland.public.cpp.borlandcpp From : Greg Chicares Date : Mon Dec 13 2004 09:51 pm On 2004-12-13 6:33 PM, Rick wrote: > > class X{}; > class Y: public X > { > public: > int aValue; > }; > > X *objects[10]; > > objects[0] = new Y(); > > when I want to call a property from the Y class, I don't know how to do > this. I tried typecasting but it didn't work: > someValue = (X)objects[0]->aValue; Don't cast to X: you want a Y. And don't use an explicit '(Y)' cast: it's not type checked. Use a polymorphic base class as in the example below (preferably putting common functionality into the base interface) and then use dynamic_cast. > aValue isn't a member of the X class, how to tell that objects[0] is > actually an instance of class Y? dynamic_cast can tell. Here's a complete example: #include #include #include class X { public: virtual ~X() {} }; class Y: public X { public: Y() : aValue(3) {} int aValue; }; int main() { X* objects[10]; objects[0] = new Y(); Y* yp = dynamic_cast(objects[0]); if(yp) std::cout << yp->aValue << std::endl; else throw std::runtime_error("Your error message here"); } .