Constant objects and constant member functions



Constant objects and member functions
Constant objects and member functions
Basic Concept:

A function is made into a constant function by placing the keyword const after the declarator but before the function body. If there is a separate function declaration, const must be used in both declaration and definition. Member functions that do nothing but acquire data from an object are obvious candidates for being made const, because they don’t need to modify any data.

Syntax:

For a member Function:

returnType functionName() const      // Constant member function

For an Object:

className  const objectName            //   Constant object

Example program:


A const member function can be called on a const object:
class abc
{
public:
    void const_function() const;
    void function();

private:
    int x;
};


const abc co;
abc o;

co.const_function();  // legal
co.function();        // illegal, can't call regular function on const objecto.const_function();   // legal, can call const function on a regulared objecto.function();         // legal
Furthermore, it also tells the compiler that the const function should not be changing the state of the object and will catch those problems:
void abc::const_function() const{
    x = 3;   // illegal, can't modify a member in a const object
}

Constant object can't access non-constant function.
Previous
Next Post »