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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With