I encountered a question today, found here, which raised this question for me.
Here\'s a pseudo-code example of what I\'m getting at:
class Car{
publ
Now if there are more than one type of cars which is retractable, say such cars are CarA, CarB, and CarC (in addition to Lamborghini), then are you going to write this:
if(Lamborghini* lambo = dynamic_cast(cars[i])) {
lambo->retractTheRoof();
}
else if(CarA * pCarA = dynamic_cast(cars[i])) {
pCarA->retractTheRoof();
}
else if(CarB * pCarB = dynamic_cast(cars[i])) {
pCarB->retractTheRoof();
}
else if(CarC * pCarC = dynamic_cast(cars[i])) {
pCarC->retractTheRoof();
}
So a better design in such cases would be this: add an interface called IRetractable and derive from it as well:
struct IRetractable
{
virtual void retractTheRoof() = 0;
};
class Lamborghini : public Car, public IRetractable {
//...
};
class CarA : public Car, public IRetractable {
//...
};
class CarB : public Car, public IRetractable {
//...
};
class CarC : public Car, public IRetractable {
//...
};
Then you can simply write this:
if(IRetractable *retractable = dynamic_cast(cars[i]))
{
retractable->retractTheRoof(); //Call polymorphically!
}
Cool? Isn't it?
Online demo : http://www.ideone.com/1vVId
Of course, this still uses dynamic_cast, but the important point here is that you're playing with interfaces only, no need to mention concrete class anywhere. In other words, the design still makes use of runtime-polymorphism as much as possible. This is one of the principle of Design Patterns:
"Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18)
Also, see this:
Other important point is that you must make the destructor of Car (base class) virtual:
class Car{
public:
virtual ~Car() {} //important : virtual destructor
virtual int goFast() = 0;
};
Its imporant because you're maintaining a vector of Car*, that means, later on you would like to delete the instances through the base class pointer, for which you need to make ~Car() a virtual destructor, otherwise delete car[i] would invoke undefined behaviour.