C++ Why isn't the second expression valid?
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!
The second expression is perfectly valid. You may be misinterpreting something the solution is saying. Maybe it's not saying it's syntactically invalid, but has some other problem.
It does seem a little odd and suspicious to do that when the classes you're working with have no virtual functions.
My inclination is that the homework solution is just flat out wrong. But it seems odd for it to get something so simple wrong.
Sorry, but I have verified that your codes works well in Visual Studio 2010, except you missed a semicolon at the end of class Vehicle.
SLaks has explained why that expression isn't safe, but it is legal.
According to Comeau, the only error is a missing semicolon on the end of class Vehicle {} /* HERE */
.
精彩评论