Given the following code:
#include <iostream>
#include <string>
using namespace std;
class A
{
private:
string m_name;
string m_first;
public:
A(): m_first("string") {}
virtual void print() const {}
string& getName() const {return m_first;} // won't compile
const string& getLastName() const {return m_name;} // compile
};
int main()
{
A a;
return 0;
}
Compiler presents : "invalid initialization of reference of type 'std::string&' from expression of type 'const std::string'"
Why can't I return "m_first" from getName() ? I thought that the const on the tail of the function states that the function will not change 'this'... but I'm not trying to change this , just return a data member.
Because inside a const method, all non-mutable
members are implicitly const
. So, you're trying to bind a reference to non-const std::string
(your return value) to an object of type const std::string
, which is illegal(because it would allow modification of const data), hence the error.
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