Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Why isn't the second expression valid?

Tags:

c++

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.

like image 686
helpermethod Avatar asked Jan 21 '23 08:01

helpermethod


1 Answers

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!

like image 131
JaredPar Avatar answered Jan 22 '23 21:01

JaredPar