+ 1
Const
What are consts usually used for? I mean I literally never use const and I was wondering if using it could make things easier
4 Answers
+ 2
Const correctness is a powerful concept. I'll first outline the typically use cases:
1) const variables as Avinesh describes
2) const input parameters on a function - cannot be modified in the scope of that function
3) const function (for class functions only). The function cannot modify the class member data
4) returning a const reference to a class member variable - the data is accessed without copying but cannot be modified
Basically const allows you to define what can and can't change. The compiler will error when const rules are violated, thus protecting the dev(s) from making mistakes. This becomes more important when passing objects round, because the tendency is to pass objects by reference (to avoid copying data all the time) and passing by reference without const carries the risk of unintentionally modifying the data.
+ 2
(continued)
For example, suppose you have the following class:
class A
{
public:
void increment(); // non-const
void print() const; // const
};
And you had the following functions:
void Display(const A& a); // const reference
void Clear(A& a); // non const reference
Calling a.increment() inside Display would not compile because the const in the Display function conflicts with the fact that increment is non-const. Similarly we could not call Clear() inside print() - print is const and so the object cannot be modified as Clear would have done.
A lot of it is about intent - if you are in the habit of using const wherever you can, you can instantly tell when a function is going to modify something because there's no const. Often, as projects get more complex, the const related compiler errors stop you making some real blunders
+ 2
C++ does it the wrong way around. Everything should be const, without you explicitly saying it!
Then your question becomes, "What are non-consts usually used for?"
And the answer to that is, surprisingly little. Most variables you use you set once and never again. Most functions you call don't change the class they live in.
+ 1
Probably used in mathematical calculations where constants like -
pi, e, square root of 2 etc are declared as constants so that you even by mistake do not alter those values throughout the program.