-
Polymorphism question
Hi,
I have an array of base class pointers which I initialize with derived class pointers. However when I call the Run() function, only the base class one gets called.
Heres my code -
Code:
void SomeFunction()
{
Car** carArray = (Car**)new SportsCar*[100];
for(int i = 0; i < 100; ++i)
carArray [i] = new SportsCar();
CreateCars(carArray ,100);
}
void CreateCars(Car** carArray, int num)
{
Car** car = carArray;
for(int i = 0; i < num; ++i)
{
car [i]->SetSpeed(rand()%100);
}
carDriver = new carDriver(car,num);
}
class Car
{
...
virtual void Run() { cout << "CAR" << endl; }
};
class SportsCar
:public Car
{
void Run() { cout << "SPORTS CAR" << endl; }
};
All I get is a "CAR", any Ideas ? also, my Car class has a few pointers..do I need to define a copy constructor/assignment operator based on the code I posted above ?
-
If your Car class has pointers, you probably need a copy constructor, yes. I don't see where you are calling Run from in this code, though.
-
Ahh, I found the bug.. I had another array on which Run was called which held only static cars. That is why it wasnt working properly.
For the copy constructor, My car class has pointers to other classes such as Engine which have further pointers and so on. So how am I supposed to go about this ? Can someone show me an example or point me to a tutorial! anything will do..Thanks!
-
Do you want them to point at the same engine object, or should each have their own engine? If the first you can just copy the pointers. If the second, you need to make a new engine that is a copy of the other, and set the new pointer appropriately.
-
Does your class delete the pointers in the destructor? If it does, that's a good hint that you need a copy constructor (and copy assignment operator) or that you need to disable them by declaring them as private and not implementing them.
If you don't have a destructor or it doesn't delete the pointers, then you probably don't need an explicit copy constructor or copy assignment operator.