0

I am revisiting C++. I am confused about a syntax. It is not giving me any error but I don't understand how it works.

class Car {
private:
    int wheels;
public:
    void setWheels(const int numberOfWheels);
    int getWheels() const;
};

void Car::setWheels(int numberOfWheels) {
    wheels = numberOfWheels;
}
int Car::getWheels() const {
    return wheels;
}

What does const do when it is put after the method name? Shouldn't it be put before the return type of the method?

Natasha
  • 6,651
  • 3
  • 36
  • 58
  • In C++, member function `int getWheels() const;` is equivalent to (in pseudo-code) `int getWheels(Car const* this);`. The `const` suffix indicates that the `this` is a const pointer. – Eljay May 29 '18 at 19:37
  • In other words, a `const` method cannot modify any member variables of the object or call any non `const` methods of that object, essentially. – Paul Sanders May 30 '18 at 04:55

0 Answers0