C ++ Why does the second expression not work?

Suppose you have the following hierarchy of objects:

class Vehicle { public: virtual ~Vehicle() {} }; class LandCraft: public Vehicle {}; class Truck: public LandCraft {}; 

Now we have two expressions:

 Truck truck; Vehicle& vehicle = truck; 

According to the homework decision, the second expression is not valid. But why? My compiler does not complain at all, and I do not see what should be wrong here.

+4
source share
4 answers

It seems like homework is wrong. There is nothing wrong with initializing a reference to a base type from a derived instance.

EDIT

As several people have noted (notably Slaks), while there is nothing wrong with this statement, it does create potential future mistakes in the future. This allows you to arbitrarily place any Vehicle in the place that Truck expects. For example, consider the following

 Truck truck; Vehicle& reallyATruck = truck; reallyATruck = LandCraft(); 

Oops!

+6
source

The second expression is excellent. You may be misinterpreting the solution. Perhaps this does not mean syntactically invalid, but it also has other problems.

It seems a little strange and suspicious for this when the classes you work with do not have virtual functions.

My tendency is that homework is simply wrong. But it seems strange that he can do something so simple.

+1
source

Sorry, but I confirmed that your codes work well in Visual Studio 2010, except that you skipped the semicolon at the end of the Vehicle class.

+1
source

SLaks explained why this expression is unsafe, but it is legal.

According to Como, the only mistake is the lack of a semicolon at the end of class Vehicle {} /* HERE */ .

+1
source

Source: https://habr.com/ru/post/1341671/


All Articles