2

why is the purpose of "const" in that case?

std::string List::reqClubName() const
{
    return m_Club;
}

Thanks

  • Not exactly, the method I am using does not use any parameters () –  Apr 06 '14 at 03:35
  • 1
    So const in my case is to make sure the method does not modify anything. Am I right? –  Apr 06 '14 at 03:37
  • @user2984887 indeed. They can't change any members of the variable, unless they were declared mutable. – AliciaBytes Apr 06 '14 at 03:39

2 Answers2

4

Banning the modification of members is not the only reason to qualify a member function as const. Whether you want to modify members or not, you can only call a member function on an object through a const context if the member function is marked const:

#include <iostream>
#include <string>

struct List
{
   std::string reqClubName()
   {
      return m_Club;
   }

private:
   std::string m_Club;
};

int main()
{
   const List l;
   std::cout << l.reqClubName();
   // ^ illegal: `l` is `const` but, `List::reqClubName` is not
}

Neither the language nor the compiler care that reqClubName doesn't try to modify the object anyway; your program will not compile.

Because of this, a const suffix should be your default approach unless you do need to modify a data member.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

The const after a member function says that the function does not modify member data in the class it is a part of.

Warren Dew
  • 8,790
  • 3
  • 30
  • 44