Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Qualifiers dropped in binding reference of type x to initializer of type y

Tags:

c++

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?

like image 579
Jimmyt1988 Avatar asked May 10 '15 00:05

Jimmyt1988


2 Answers

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
like image 82
Benjamin Lindley Avatar answered Nov 16 '22 14:11

Benjamin Lindley


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.

like image 1
Khanh Avatar answered Nov 16 '22 16:11

Khanh