<DJ*********@gmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
Hi,
I have a vector (myVector) of BaseClass objects. I store in it a
DerivedClass object (where DerivedClass inherits from BaseClass). Later
I want to get the last element in the vector and store it in a
DerivedClass variable, doing:
DerivedClass d =
(DerivedClass)myVector[(int)dataTablesVector.size()-1];
this gives me the following error:
error C2440: 'type cast' : cannot convert from
'std::allocator<_Ty>::value_type' to 'DerivedClass'
with
[
_Ty=BaseClass *
]
Where am I going wrong?
Forget the code. The logic doesn't make sense. Why are you storing base
class objects in a Derived class? Can you store a vector of vehicles in a
car? Would you store a vector of shapes in a triangle? Why would you store
Animals in a Chicken?
Inheritence only works when a strict relationship exists between the base
and its derivative. Its an exceptional relationship.
Storing a type in a class is called composition. A Car has a motor. A truck
has a vector of wheels. An airplane has a landing gear. A building has a
vector of floors. A Ferry can hold vehicles, etc...
Also, as already mentioned to you, casting is not guesswork in C++. This is
a language with strong type checking which extends to its casting mechanisms
(static_cast, dynamic_cast, etc). Casting from a base class to a derived
class implies that the object is a derived object to begin with.