Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why '&' changes the behaviour of the object?

Tags:

c++

oop

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() ?

like image 784
Ravi Shenoy Avatar asked Nov 29 '22 02:11

Ravi Shenoy


1 Answers

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".

like image 82
Pete Becker Avatar answered Dec 05 '22 10:12

Pete Becker