I think I can give a nice example of the usefulness of base and derived classes. I'll give it a shot:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
class Vehicle
{
public:
virtual void Start() = 0;
virtual void Stop() = 0;
virtual void Accelerate() = 0;
virtual float get_Speed() = 0;
}
class Car : Vehicle
{
override void Start()
{
cout << "You properly started this car!";
}
//Something like the sort goes for the other functions.
...
}
class Airplane : Vehicle
{
override void Start()
{
cout << "You properly started this airplane! You rock.";
}
...
}
class Helicopter : Vehicle
{
override void Start()
{
cout << "You properly started this helicopter. Is there anything you can't do??";
}
...
}
|
Now, with those classes you can choose to create 3 different functions to start, accelerate, and stop a car, an airplane, and a helicopter respectively, OR you can do it the cool way: One function that start, accelerate, and stop any vehicle.
Because I have so much money and have a garage full of cars, airplanes, and helicopters, I want to group all of them into an array so I can have them handy. Note that this is NOT possible if you don't use polymorphism (it is possible, but it is a big fat pain in you know where).
1 2
|
//Declare the array of ... what? Cars? No. Airplanes?? No!! Vehicles!!
Vehicle[] myVehicles = { new Car(), new Airplane(), new Airplane(), new Car(), new Helicopter(), new Helicopter() };
|
If I didn't have the base Vehicle class, I could never group my garage contents into a single array.
Now, let's drive all of them:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
void TestDriveThis(Vehicle *vehicle)
{
vehicle->Start();
float currentSpeed = 0;
float targetSpeed = 150;
while (currentSpeed < targetSpeed)
{
vehicle->Accelerate();
currentSpeed = vehicle->get_Speed();
}
//You reach the target speed, now get your foot off the pedal and say hello to the ladies along the road.
while (currentSpeed > 0)
{
SayHelloToNurses();
}
vehicle->Stop();
}
...
int main()
{
for(int i = 0; i < 6; i++)
{
TestDriveThis(myVehicles[i]);
}
return 0;
}
|
Without the base class Vehicle, I wouldn't have been able to collect all of my vehicles in a single array, and I wouldn't have been able to test drive them all using the same function. Instead, I would have had to have 3 different arrays (one for cars, one for airplanes, and one for helicopters), and I would have had to have 3 different TestDriveThis() functions, again, one for cars, one for airplanes, and one for helicopters.