Hello! Please help me understand the concept of inheritance. Actually, I'm not even sure inheritance is what I'm trying to do here. Let me explain: Suppose I have a class Vehicle that is inherited by two classes Car and Bicycle:
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 37
|
class Vehicle {
public:
Vehicle() {
// ...
}
~Vehicle() {
// ...
}
};
// A Bicycle IS A Vehicle
class Bicycle : Vehicle {
public:
Bicycle() { /* … */ }
~Bicycle() { /* … */ }
void Stop() { /* … */ }
void Go(int feet) { /* … */}
void TurnLeft() { /* … */ }
void TurnRight() { /* … */ }
private:
/* … */
};
// A Car IS A Vehicle
class Car : Vehicle {
public:
Car();
~Car();
void Stop() { /* … */ }
void Go(int miles) { /* … */ }
void TurnLeft() { /* … */ }
void TurnRight() { /* … */ }
private:
/* … */
};
|
Now, both Cars and Bicycles can Stop, Go, and Turn, but they both do all of those actions in different ways (this is why we cannot put them in the base class; we put them in the derived ones because they have separate implementations).
However, we can define outside functions that only utilize their public member functions, and that's all they need; these functions can handle either a Car or a Bicycle. It doesn't care what kind of a vehicle it is, because the path to get to work or to the mall is the same:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
void GoToWork(Vehicle AnyVehicle)
{
AnyVehicle.TurnLeft();
AnyVehicle.Go(2);
AnyVehicle.TurnRight();
return;
}
void GoToTheMall(Vehicle AnyVehicle)
{
AnyVehicle.TurnRight();
AnyVehicle.Go(3);
AnyVehicle.TurnRight();
AnyVehicle.Go(1);
AnyVehicle.TurnLeft();
return;
}
|
Unfortunately, the problem with this is that it doesn't work:
1 2 3 4 5 6 7 8 9 10 11 12
|
int main()
{
Bicycle MyBike;
// ERROR: Expects a Vehicle... and gets a Vehicle?!?!?!
GoToWork(MyBike);
Car MyCar;
GoToTheMall(MyCar);
return 0;
}
|
My question is: why doesn't this work? On the call to GoToWork the compiler tries to convert MyBike to a Vehicle and fails. But MyBike is a Vehicle!