Alex Rivera | Logout

How many and which are the uses of "const" in C++?

Asked 2009-01-18T17:25:23.067
155

As a novice C++ programmer there are some constructs that look still very obscure to me, one of these is const. You can use it in so many places and with so many different effects that is nearly impossible for a beginner to come out alive. Will some C++ guru explain once forever the various uses and whether and/or why not to use them?

Edit
Report

1 Answer

33

There are really 2 main uses of const in C++.

Const values

If a value is in the form of a variable, member, or parameter that will not (or should not) be altered during its lifetime you should mark it const. This helps prevent mutations on the object. For instance, in the following function I do not need to change the Student instance passed so I mark it const.

void PrintStudent(const Student& student) {
  cout << student.GetName();
}

As to why you would do this. It's much easier to reason about an algorithm if you know that the underlying data cannot change. "const" helps, but does not guarantee this will be achieved.

Obviously, printing data to cout does not require much thought :)

Marking a member method as const

In the previous example I marked Student as const. But how did C++ know that calling the GetName() method on student would not mutate the object? The answer is that the method was marked as const.

class Student {
  public:
    string GetName() const { ... }
};

Marking a method "const" does 2 things. Primarily it tells C++ that this method will not mutate my object. The second thing is that all member variables will now be treated as if they were marked as const. This helps but does not prevent you from modifying the instance of your class.

This is an extremely simple example but hopefully it will help answer your questions.

answered 2009-01-18T17:34:43.530

Your Answer