-4

What does it mean when const is a part of the method type

const std::string& getName();

and when const is at the end of the method

const std::string& getName() const;

Thanks a lot.

Neculoiu Vlad
  • 35
  • 1
  • 7

1 Answers1

1

It means that the definition of that function cannot modify the structure/class it is part of (i.e. it cannot mutate instance variables).

struct MyStruct
{
    int i ;
    void go1 ()
    {
        i = 5 ;
    }
    void go2 () const
    {
        i = 5 ; // error: 'this' is const
    }
} ;
iAdjunct
  • 2,739
  • 1
  • 18
  • 27