21

why does the following throw this error:

IntelliSense: qualifiers dropped in binding reference of type "string &" to initializer of type "const string"

.h

class A
{
public:
    wstring& GetTitle() const;
private:
    wstring title;    
};

.cpp

wstring& GetTitle() const
{
    return this->title;
}

If i remove the const word, it stops complaining, and yet i have never made any changes to the variable?

Jimmyt1988
  • 20,466
  • 41
  • 133
  • 233
  • possible duplicate of [binding of reference to a value of type drops qualifiers](http://stackoverflow.com/questions/27812119/binding-of-reference-to-a-value-of-type-drops-qualifiers) – CinchBlue May 10 '15 at 00:57
  • I read that question before, and got nothing from it heheh.. So i guess this one is more useful! – Jimmyt1988 May 10 '15 at 00:58
  • The first answer's first paragraph says the same as the first answer here. The issue is the same, but clarity requires an edit, not a new question. – CinchBlue May 10 '15 at 01:03
  • GetTitle function should return wstring instead of wstring& – Li Kui Jul 04 '19 at 01:23

2 Answers2

30

By returning a non-const reference to a member of your class, you are giving the caller access to the object as if it's non const. But GetTitle, being a const function, does not have the right to grant that access.

For example:

A a;
string& b = a.GetTitle(); // Allows control over original variable
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • ahhhh, is that because if they called the function and returned it into a `string&` instead of a `string` they could change the original value? Or am i off completely? – Jimmyt1988 May 10 '15 at 00:55
  • Hurrahhh, thanks buddy! marking as correct when i can! – Jimmyt1988 May 10 '15 at 00:55
  • This is a duplicate question. – CinchBlue May 10 '15 at 00:57
  • 11
    @Cinch: It may be. But not of the question you linked. Just because the error message is the same, does not mean the question is. This one involves a const member function, and while the connection may be obvious to you or me, it will not be to a beginner. – Benjamin Lindley May 10 '15 at 01:08
3

You can add const before the reference that would resolve the conflict as well, i.e. const wstring& GetTitle() const; and likewise for the .cpp file.

Khanh
  • 57
  • 7