Christine
Christine

Reputation: 113

invalid initialization of non-const reference of type 'std::string&

const string& mtm::RadioManager::getBestSong() const {    
    string& most_popular_song=tmp.getName();    
    most_popular_song = current_song.getName();    
    return most_popular_song;
}

string mtm::Song::getName() const {    
    return this->song_name;
}

class Song {    
    string song_name;

public:

string getName() const;
}

I get this error:

invalid initialization of non-const reference of type 'std::string& {aka std::basic_string&}' from an rvalue of type 'std::string {aka std::basic_string}'

I can't make it const string& most_popular_song=tmp.getName(); because I'm changing it to tmp.getName(); That returns string! What should I do to get rid of this error?

Upvotes: 1

Views: 6186

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320371

Function getName does not provide modifying access to the underlying song_name field of the class. You can't change song_name through getName (as written) regardless of what you do. This is the whole point of having getName to return a copy of the song_name field.

For this reason receiving the result by non-constant reference makes no sense whatsoever. You can't change it anyway. And even if you do somehow, it will have no effect on song_name.

Under these circumstances, it is completely not clear what you are trying to do by

string& most_popular_song=tmp.getName();    
most_popular_song = current_song.getName();    

sequence and what the point of all these manipulations is.

If you want to be able to modify the song_name field, you have to return a reference to song_name from getName

string &mtm::Song::getName() const {    
    return this->song_name;
}

This will fix your error, but this will basically defeat most of the protection and isolation provided by the getName function. What was the point of making song_name private, if you immediately and fully expose it to outside world through a nopn-const reference returning getName function?

A better idea would be to write a setName function and use it to modify the song_name, instead of trying to obtain direct reference access to song_name.

Upvotes: 2

Related Questions