Gurus everywhere tell us to const
everything unless we need to modify it, yet the standard makes everything mutable until we declare it const
.
Am I missing something here, or is this a contradiction? Why aren't C++ types const
by default when, according to the experts (some of whom presumably designed the standard), they should be made const
by default?
History. const was introduced by Bjarne Stroustrup in C with Classes, the predecessor to C++, in 1981, and was originally called readonly .
Yes. const is there in C, from C89.
By default, an integer constant is of type int .
No, const does not help the compiler make faster code.
The same goes for const member variables in classes, the only difference with non-const member variables is that when we try to modify them we will get the same compile error shown above.
Data Types can also be classified as shown in the image below – Primitive, Derived and User Defined. Primitive data types are the first form – the basic data types (int,char,float,double). Derived data types are a derivative of primitive data types known as arrays, pointer and function.
Another important point is the one that we discussed above, when you declare a const object of type T, you can only call const functions. That’s because you can’t convert a pointer to a const object to a pointer to a non-const object because it would violate constness.
There are 4 types of constants in C. By definition, a constant is a quantity that does not change throughout the execution of a program. An integer constant is an integer quantity which contains a sequence of digits.It should not have a decimal point.
Gurus everywhere tell us to const everything unless we need to modify it,
That's been conventional wisdom for a decade or two, yes.
yet the standard makes everything mutable until we declare it const.
The standard has evolved from languages developed around fifty years ago, when const-correctness, and even type checking, were largely regarded as being only of academic interest.
Am I missing something here, or is this a contradiction?
It's not a contradiction; just a language that doesn't work how some would say it should. You still can (and should) declare things const
where appropriate, and we just have to put up with a language that doesn't push us towards safe practices.
Why aren't C++ types
const
by default?
Because changing such a fundamental aspect of the language will break just about all existing code. That's a much bigger concern than slightly reducing the scope for mistakes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With