About calling an subclass' overriding method when casted to its superclass
- by Omega
#include <iostream>
class Vehicle {
public:
void greet() {
std::cout << "Hello, I'm a vehicle";
}
};
class Car : public Vehicle {
public:
void greet() {
std::cout << "Hello, I'm a car";
}
};
class Bike : public Vehicle {
public:
void greet() {
std::cout << "Hello, I'm a bike";
}
};
void receiveVehicle(Vehicle vehicle) {
vehicle.greet();
}
int main() {
receiveVehicle(Car());
return 0;
}
As you can see, I'm trying to send a parameter of type Vehicle to a function, which calls greet().
Car and Bike are subclasses of Vehicle. They overwrite greet().
However, I'm getting "Hello, I'm a vehicle".
I suppose that this is because receiveVehicle receives a parameter of type Vehicle instead of a specific subclass like Car or Bike. But that's what I want: I want this function to work with any subclass of Vehicle.
Why am I not getting the expected output?