Const declaration:

const int* x; //constant data (*x); non-constant pointer
int const *x; //same as above
int * const x; //constant pointer; non-constant data
const int * const x; //const data; const pointer

Const member functions:
Function values can be declared const. Helps specifically in operator overloading.

const Foo operator*(const Foo& lhs, const Foo& rhs);

Foo a,b,c; 

a = b*c; //legal
(a*b) = c; //This will work if return value is not const

It is not useful to assign any value to the product of two variables but it can happen accidentally. Example, using = instead of ==

if(a*b = c) {
}

Const member functions in a class cannot modify the contents of the class. They make it possible to work with const objects. Member functions differing only in their “constness” can be overloaded.

class Foo {
public:
    const int& value() const;
       int& value();

private:
    int x;
};

main() {
    Foo x(1);
    cout<<x.value(); //Non-const function is called

    const Foo y(2);
    cout<<y.value(); //const function is called
}

Bitwise Constness:
C++ gives only bitwise constness. This means const member functions cannot modify pointers in a class. But they can modify the data the pointer points to.

Mutable:
Mutable type modifier allows variables to be modified even by const functions.

Class Foo {
public:
    void test() const; //can modify x but nor y
private:
    mutable int x;
    int y;
};

Tags: , ,