I am having trouble with I believe Downcasting.
There are two classes, a base class and an inherited class.
What I'm trying to do is store refernces to the two mixed classes within a single list
but when I push the reference to the object into the list, it looses it's non base class datamembers
I believe I need to Downcast, and so am trying to , but am still loosing the datamembers
Base Class:
Code:class Vehicle { public: Vehicle(int publicmpg = 0); protected: int privatempg; }; Vehicle::Vehicle(int publicmpg) { privatempg = publicmpg; }
Derivied Class:
main:Code:class SportsCar : public Vehicle { public: SportsCar(int publicsixspeed = 0, int publicmpg = 0); protected: int protectedsixspeed; }; SportsCar::SportsCar(int publicsixspeed, int publicmpg) : Vehicle(publicmpg) { protectedsixspeed = publicsixspeed; }
Code:#include <iostream> #include <list> #include "Vehicle.h" using namespace std; int main() { list<Vehicle> listname; int publicmpg = 0; int publicsixspeed = 0; int publicelectricroof = 0; SportsCar node(publicmpg, publicsixspeed); SportsCar *ptrToSportsCar; //attempting to correct the problem by Downcasting ptrToSportsCar = dynamic_cast<Vehicle*>(&node); //Push the SportsCar object onto the list, but inhertited datamember 'protectedsixspeed' is lost. listname.push_back( *ptrToSportsCar ); system ("PAUSE"); return 1; }
Visual studio reports:
I've just moved house and stuck on dialup, so have read the book I havecannot convert from 'Vehicle *' to 'SportsCar *'
on the subject, and this is what I have come up with after reading it.
It compiles and is what I can gather from my book
as to be correct, but seems is not right.
Could anyone provide a solution at all?
It would be most appreciated.
Thank you !



LinkBack URL
About LinkBacks


