Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why return string& from a const method won't compile?

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.

like image 717
Ron_s Avatar asked Aug 29 '11 13:08

Ron_s


1 Answers

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.

like image 87
Armen Tsirunyan Avatar answered Oct 10 '22 03:10

Armen Tsirunyan