About calling an subclass' overriding method when casted to its superclass
Posted
by
Omega
on Stack Overflow
See other posts from Stack Overflow
or by Omega
Published on 2013-10-20T21:45:47Z
Indexed on
2013/10/20
21:54 UTC
Read the original article
Hit count: 172
c++
|inheritance
#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?
© Stack Overflow or respective owner