C++ const keyword

In C++, the keyword const means different things according to its context.

 

Variable:

When you add const in front of a variable, it means that variable is treated like a constant.

You will not be able to change the value of a const variable once you assign it.

An example of its usage would be:

const float PI = 3.14156;

Object

If an object is declared as const, then only the const functions may be called.

Member Function

If const is used with a member function, that means only const objects can call that function.

For example, suppose you have the following class:

[Foo.H]

class Foo {

public:
   
void ChangeValue(int newVal) { m_val = newVal; }
    int GetVal() const { return m_val; }

    const float PI = 3.14156;

protected:
    int m_val;

};

If an instance of foo is declared as const, you cannot call ChangeValue on it. Correspondingly, since GetVal is declared const it cannot modify m_val.

Parameters

Parameters in a function may be declared const, which means that those parameters will not be changed during the function call.

For example, consider the following function:

int multiply(const int a, const int b) { return a*b; }

Now, does this mean that only constants can be passed into multiply?

No. Rather, it means that during this function, the parameters a and b will be treated as constants.

Why use const?

 

Efficiency.

If you use const liberally and correctly there is a chance the compiler might be able to perform a few optimizations.

 

Readability:    Declaring parameters and/or functions as const improves program readability.

If you declare a function const, for example, anyone reading your code will know right away that the function doesn't change the object on which it is called. In addition, the compiler will return an error if a const function modifies its object, or if a const parameter is modified in its function.

 

© Lynne Grewe