I'm studying C++ form Thinking in C++ V1. I came across an example that demonstrates inheritance. Here it goes
#include <iostream>
class Instrument{
public:
virtual void play(){
std::cout<<"instrument::play()";
}
};
class Wind: public Instrument{
public:
void play(){
std::cout<<"Wind::play()";
}
};
void tune(Instrument& i){
i.play();
}
int _tmain(int argc, _TCHAR* argv[])
{
Wind flute;
tune(flute);
return 0;
}
This outputs Wind::play()
on the console.
But if I change the method 'tune' to
void tune(Instrument i){
i.play();
}
The output will instrument::play()
Since the '&' is added so that the reference of flute is passed instead of a copy, why does the program output instrument::play()
instead of Wind::play()
?
Because the copy that gets passed has type Instrument
, not type Wind
, because Instrument
is the type that the function takes. This is known as "slicing".
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