0

I'm having a question on my following code. When it's declaring the function get_name() in the class, what would be the purpose of putting the const in front of it. And what will happen if I take it off?

class College

{

string name;

const string get_name()

{ return name; }

void set_name(string n)

 { name = n; }

};

int main()

{

   College college_obj;

    return 0;

}
  • Would you mind to tell me in what case this 'const' is gonna make a difference? –  Mar 15 '18 at 08:35
  • 1
    My recommendation is: put const consistently to the right of what it refers to (`int const n`, `int const* ptr`, `int * const cptr`). Might look unfamiliar at the beginning, but avoids any confusion to where const belongs to. Sure, you need to be able to read the other way round, too, but you'll be going to swap in mind then... – Aconcagua Mar 15 '18 at 08:54
  • `std::string const get_name()` vs. `std::string get_name() const` - first variant: const refers to string, second: to entire function. Wouldn't you agree it is clearer this way? – Aconcagua Mar 15 '18 at 08:56

2 Answers2

2
const string get_name()

means that the return value is constant object. It prevents the caller of the function from calling non-const methods on the temporary return value, e.g.

x.get_name() = "bla"
x.get_name()[0] = 'a';

will not compile.

I think one of the main motivations was to prevent accidental assignments e.g. in if statements:

if (x.get_name() = "John Doe"))

It has been a guideline for some time, but C++11 made it obsolete by introducing rvalue references and move semantics.

In your example, ypu should probably return a const reference to name. This will save you the creation of temporary object and keep the benefits of being const. And the method should be declared const because it does not modify the object's state.

const& get_name() const { return name; };
Jens
  • 9,058
  • 2
  • 26
  • 43
2

I would add that

const string get_name()

somehow does not make sense, since it returns a new object. Why would you want to declare this const?
Well, of course there are always reasons, but I normally would not use that.

The usage of const is much more important when returning a reference. Then you would distinguish between:

const string& get_name() const;

and

string& get_name();
Rene
  • 2,466
  • 1
  • 12
  • 18
  • It prevents accidental modification of the temporary return value, e.g. `if (x.get_name() = "John Doe")` or `x.get_name()[0] = 'a'`. – Jens Mar 15 '18 at 09:46