Suppose you have the following object hierarchy:
class Vehicle {
public:
virtual ~Vehicle() {}
};
class LandCraft: public Vehicle {};
class Truck: public LandCraft {};
Now, we have the two expressions:
Truck truck;
Vehicle& vehicle = truck;
According to a solution to a homework, the second expression is not valid. But why? My compiler doesn't complain at all, and I don't see what should be wrong here.
It sounds like the homework solution is incorrect then. There is nothing wrong with initializing a reference to a base type from an instance of a derived.
EDIT
As several people have pointed out (Slaks in particular) while there is nothing wrong with this statement in itself, it does provide the potential for future errors down the road. It allows you to arbitrarily put any Vehicle
into a place which expects a Truck
. For example consider the following
Truck truck;
Vehicle& reallyATruck = truck;
reallyATruck = LandCraft();
Whoops!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With