Constant Objects and Constant Member Functions


Constant Objects

An object of a class may be declared to be const, just like any other C++ variable. For example:

const Date birthday(7, 3, 1969);

declares a constant object of the Date class named birthday.

The const property of an object goes into effect after the constructor finishes executing and ends before the class's destructor executes. So the constructor and destructor can modify the data members of the object, but other methods of the class can't.

Only constant member functions can be called for a constant object:

birthday.set_month(12);     // Syntax error.

Constant Member Functions

You can declare a member function of a class to be const. This must be done both in the function's prototype and in its definition by coding the keyword const after the method's parameter list. For example:

class Date
{
private:

    int month;
    int day;
    int year;

public:

    Date();
    Date(int, int, int);
    void set_month(int);
    int get_month() const;     // This function does not change modify data members of the object that calls it.
    ...
};

int Date::get_month() const
{
    return month;
}

The this pointer passed to a const member function is a pointer to a const object. That means the pointer can not be used to modify the object's data members. Any attempt to change a data member of the object that called a constant method will result in a syntax error, as will attempting to call a non-const member function for that object.

Constant objects can only call constant member functions. Non-constant objects can call both constant and non-constant member functions.

A constant member function can be overloaded with a non-constant version. The choice of which version to use is made by the compiler based on whether or not the object used to call the member function is constant.

Constructors and destructors can never be declared to be const. They are always allowed to modify an object even if the object itself is constant.

Member functions that are static can't be declared to be const. The const keyword modifies the this pointer that is passed to a member function, but static member functions don't a this pointer since they can be called without an object.

As a general rule:

Any non-static member function that does not modify the data members of the object that called it should be declared to be const. That way it will work with constant objects.