1

I'm learning C++ i saw a const after an operator function.
It doesn't make sense because the function returns the same value regardless of the const.
What's the purpose of using it?

using namespace std;

class Person {
public:
    int age;
    Person(int age) : age(age) {}

    int operator *(int &b) const {
        return b;
    }
};

int main() {
    Person *p = new Person(11);

    int a = 19;

    cout << *p * a; // prints 19

    delete p;
}
Jacqueline
  • 53
  • 2
  • 5
  • 1
    [OT]:- >`Person p(11);` (and `std::cout << p * a;`). So you avoid memleak. – Jarod42 Jan 13 '22 at 15:25
  • 1
    The linked explanation is a bit wordy, tl;dr: it tells the compiler "this is safe to call on `const Person` objects". –  Jan 13 '22 at 15:26
  • @Jarod42 Fixed it. – Jacqueline Jan 13 '22 at 15:29
  • 1
    There is an implicit `this` pointer on member functions. It's *as if* the member function was `int operator*(Person* this, int& b);` free-standing function. And with the trailing `const`, *as if* the function was `int operator*(Person const* this, int& b);` free-standing function. Because the `this` is implicit, when `const` was added to the language around 1989, Bjarne had to figure out how to qualify const from non-const member functions with a backwards compatible syntax. – Eljay Jan 13 '22 at 15:58

1 Answers1

5

A const operator behind a member function applies to the this pointer, i.e. it guarantees that the object you call this function on may not be changed by it. It's called a const-qualified member function

If you tried, in this example, to change the persons age in the operator*(), you would get a compile error.

Benjamin Buch
  • 4,752
  • 7
  • 28
  • 51
eike
  • 1,314
  • 7
  • 18