I've written a program in which I have a base class(named "Account") and some sub-classes. the subclasses have some extra attributes which the base class do not. there's a vector in my program, in which I keep the objects of any of the subclasses' types. since there are various subclasses and I wanna keep the built objects in a single vector, I have declared the vector to be of type "Account".
when I wanna access the attributes exclusive to any of the subclasses via the objects of the vector "account", it gives this error:
class Account has no member "the specified attribute X".
I know I have declared my vector as an Account-typed one; which lacks attribute X; but the object is actually of type subclass Y and while being constructed, it has a built-in attribute Y. has it somewhat truncated Y, when being pushed_backed into the vector <Account>?
if not, how can I access this attribute mentioned?
Unfortunately, because accounts is a vector<Account>, there is no way to access those attributes as you are dealing with Account objects, not objects of the derived classes. Basically, you have the pain of type slicing.
A few solutions exist, e.g., you could use a std::vector<std::tr1::shared_ptr<Account> > instead, or use a std::vector<Account*> and then do some manual memory management. Or if you have access to Boost, you could use a boost::ptr_vector<Account>.
However, even if you do use any of these solutions, it would be more ideal if you made better use of polymorphism, e.g., you have a virtual member function that derived classes override such that their extra attributes are used in these overrides.
But if you really do need to know about derived classes when dealing with this vector of (smart) pointers to Account, then use dynamic_cast to cast (with checking) from an Account pointer to the desired derived class pointer.
would you plz explain it a little bit more? I'm having difficulties figuring out what I should do exactly.
What you need to do next, exactly, is look up some of the terms and jargon from laserlight's post.
Originally Posted by Farnaz
That post captures, quite simply, what you need to do and some options for doing it. However, you do need to understand the terms used to be able to apply it.
ok...guess you're right. thank you anyway.