Julien Ganis
Julien Ganis

Reputation: 81

I can't find the utility of the second const in this part of c++ code, can someone explain please?

const T & top() const { return m_Data.back(); }

Upvotes: 3

Views: 119

Answers (4)

Luchian Grigore
Luchian Grigore

Reputation: 258648

Michael's answer covers just about everything, but there are some other aspects:

  • You're only allowed to call const methods inside a const method.
  • You can change members if you declare them as mutable.
  • You won't be able to change any other members of the class.

Upvotes: 2

lvella
lvella

Reputation: 13491

This syntax if for methods, inside classes. Methods marked as const (the second const in your code) can not modify the attributes of the object, only read. Const methods are the only callable methods if you instantiate your object as const. For intance:

class A {
public:
  void put(int v) {
    var = v;
  }

  int read() const {
    return var;
  }

private:
  int var;
}

int main() {
  A obj;
  obj.put(3);

  const A obj2 = obj;
  obj2.read(); // OK, returns 3;
  obj2.put(4); // Compile time error!
}

Upvotes: 3

Mahesh
Mahesh

Reputation: 34625

Only member functions can be const qualified, non-member functions can not. The same is true for C++ too. C has no concept of member functions and hence they can not.

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143269

It means that this pointer in member function is const. In other words that the call doesn't modify the object. (and whatever reference/pointer it returns will also be const).

Upvotes: 6

Related Questions