Sobes.tech
Junior

Tell about constant methods in C/C++.

sobes.tech AI

Answer from AI

A constant method is a class method declared using the const keyword after the parameter list. It guarantees that the method does not modify the state of the class object (this).

Main properties and applications:

  • Immutability guarantee: Inside a constant method, you cannot directly or indirectly modify the non-static data members of the object.
  • Call for constant objects: Constant methods can be called on both constant and non-constant objects. Non-constant methods can only be called on non-constant objects.
  • Overloading: A method can be overloaded based on the constness. This allows having two methods with the same signature (name and parameters), but one will be constant, and the other — not.
  • Application: Used for accessor methods (getters) that simply return the value of a data member without modifying the object, as well as in functions that accept constant references or pointers to objects.

Example:

class MyClass {
public:
    int getValue() const { // Constant method
        // Can read member_ = 10;, but cannot write
        return member_;
    }

    void setValue(int val) { // Non-constant method
        member_ = val; // Can modify data member
    }

private:
    int member_;
};

void printValue(const MyClass& obj) {
    obj.getValue(); // OK: calls the constant method for a constant object
    // obj.setValue(20); // Error: cannot call non-constant method on a constant object
}