Derived types

Hi,

I'm having problems copying an array holding pointers to base and derived objects. (ie. I declare an array of pointers to the base class. I use the new operator to allocate sometimes the base class, sometimes the derived class. Now I want to copy the array and the objects it points to.)

I used typeid operator to determine the type of the object I'm pointing at, but I can't seem to dereference the pointer for use with the derived type constructor.

1
2
3
4
5
if(typeid(* tx.cars[i]) == typeid(Car) {
	cars[i] = new Car(* tx.cars[i]);
}
else if(typeid(* tx.cars[i]) == typeid(FastCar)) {
	cars[i] = new FastCar(* tx.cars[i]);


The compiler is balking at making a new FastCar because the item dereferences as a Car even though it's type is FastCar.

How do I get around this problem?
Nevermind. I'll use the default constructor and overloaded assignment operator.
Cheers!
I should clarify, the code compiles alright, but the last line wasn't resulting in the cars array getting a new FastCar. My other solution works just fine.
I should clarify, the code compiles alright, but the last line wasn't resulting in the cars array getting a new FastCar. My other solution works just fine.

You actually get a FastCar but its address is stored in an array of Car pointers. If your other solution is to declare cars as an array of FastCar pointers I'd suggest you drop it. Use a container of Car pointers and virtual functions to get around the problem of manipulating derived objects through base pointers.

More about virtual functions here -> http://cplusplus.com/doc/tutorial/polymorphism/
Last edited on
Topic archived. No new replies allowed.