why is the purpose of "const" in that case?
std::string List::reqClubName() const
{
return m_Club;
}
Thanks
why is the purpose of "const" in that case?
std::string List::reqClubName() const
{
return m_Club;
}
Thanks
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.
The const
after a member function says that the function does not modify member data in the class it is a part of.