Error: qualifiers discarded in binding link of type x to initializer of type y

why the following code throws this error:

IntelliSense: qualifiers are discarded by bindings of type "string &" for an initializer of type "const string"

.h

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

.cpp

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

If I delete the const word, it stops complaining , and yet I never made any changes to the variable?

+9
source share
1 answer

By returning a non-const reference for a member of your class, you give the caller access to the object as if it were not const. But GetTitle , being a const function, has no right to provide this access.

For instance:

 A a; string& b = a.GetTitle(); // Allows control over original variable 
+8
source

Source: https://habr.com/ru/post/986894/


All Articles