Search code examples
c++constants

Difference between const method and method with const attributes


What is the difference between const at the beginning:

const int MyClass::showName(string id){
...
}

And :

int MyClass::showName(const string id) {
...
}

And :

int MyClass::showName(string id) const{
...
}

Solution

  • const modifies the thing it's next to, like a word like "little". "A little yard with a shed" is different from "a yard with a little shed". Let's look at your code examples:

      const int MyClass::showName(string id) {
    

    The returned integer is const. This has no effect because the caller receives a copy and had no ability to modify the original anyways.

     int MyClass::showName(const string id) {
    

    The variable id is const. This means that code in showName() like id += "foo"; will be a syntax error because you aren't allowed to modify id.

      int MyClass::showName(string id) const {
    

    The method showName() is const. Suppose you have member variables of your class, for instance

    class MyClass {
      int something;
      int showName(string id) const;
    }
    

    We call showName() a const member function, meaning modifying other parts of the object isn't allowed inside showName(). Writing code in showName() like something = 1; is a syntax error because it tries to modify a member of MyClass.