Initialization and const
As we have observed many times, the type of an object defines the operations that can be performed by that object. A const
type can use most but not all of the same operations as its nonconst
version. The one restriction is that we may use only those operations that cannot change an object. So, for example, we can use a const int
in arithmetic expressions in exactly the same way as a plain, nonconst int
. A const int
converts to bool
the same way as a plain int
, and so on.
Among the operations that don’t change the value of an object is initialization—when we use an object to initialize another object, it doesn’t matter whether either or both of the objects are const
s:
int i = 42;const int ci = i; // ok: the value in ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.