Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Const after operator function c++

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 openrator*(), you would get a compile error.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading