Skip to main content

Constant object and constant function

Short answer

A const member function promises not to modify the object's data and can be called by const objects; non-const functions cannot be called on const objects. Example: class Test with const get() and non-const set(); a const object t1 can call get() but not set(), while a non-const object can call both.

Explain the relation between constant object and constant function with example.

Constant member function

A member function declared with const after its parameter list promises not to change any data member of the object. The compiler gives an error if it tries.

int getValue() const;

Constant object

An object declared const cannot be modified after creation. Its data must be set by the constructor.

const Test t(10);

Relation

  • A const object can call only const member functions (and constructor and destructor). Calling a non-const function on it is an error, since that function might modify the object.
  • A non-const object can call both const and non-const functions.
  • So const functions are the way to give read-only access to a const object. Functions that only display or return values should be made const.

Example

#include <iostream>
using namespace std;

class Test
{
    int value;
public:
    Test(int v) { value = v; }
    int get() const            // const function: cannot modify value
    {
        return value;
    }
    void set(int v)            // non-const function
    {
        value = v;
    }
};

int main()
{
    const Test t1(10);
    cout << t1.get() << endl;  // OK: const function on const object
    // t1.set(20);             // Error: non-const function on const object

    Test t2(5);
    t2.set(8);                 // OK
    cout << t2.get() << endl;  // OK, const function on normal object
    return 0;
}

Output

10
8

A mutable data member is the only member a const function may change.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 4 questions →