Click here to Skip to main content
Click here to Skip to main content

Constants in C++

, 12 Mar 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
This post explains all the uses of const keyword

Introduction

In this post, I shall be discussing about constants. This will give you the entire idea about all the different constants available in C++ programming language like constant member, member function, object, pointer, parameter, expression, iterator, casting, etc.

Description

Constant means unchangeable.

Let’s start looking into different aspects of constant. C++ offers the concept of a user-defined constant, a const, to express the notion that a value doesn't change directly. Declaring something const ensures that its value will not change within its scope. Because "constants cannot be assigned to, a constant must be initialized".

const Keyword

Note: Const restricts the ways in which an object can be used, rather than specifying how the constant is to be allocated. The initializer for constant is a constant expression but not always, if it is constant expression it can be evaluated at compile time and if it is not, the storage needs to be allocated for them. For example:

const int a1 = 1;
const int a2 = 2;
const int a3 = func(3);
Extern const int a4;
const int* p = &a2;
...

Given this, the compiler knows the values of a1 and a2 so that they can be used in constant expressions. a3 and a4 are not known at compile time, storage must be allocated for a3 and a4. Because address of a2 is taken, storage must be allocated for a2 also. The keyword “extern” indicates that a4 is defined elsewhere. Common uses of constants are as array bounds and case labels.

Constant Pointer

Please make a clear note, when using a pointer, two objects are involved: the pointer itself and the object pointed to. When const keyword is pre-fixed before declaration of a pointer, it makes the object constant and not the pointer. To declare pointer itself as constant, we use the declaratory operator '*const' instead of plain '*'. For example:

Void func(char* p)
{
Char a[] = “Hello”;
const char* pc = a;  	// pointer to constant
pc[2] = ‘r’; 		// error c1 points to constant
pc = a;			// ok

char const* cp = a;	// constant pointer
cp[2] = ‘r’;		// ok
cp = a;			// error: cp is constant

const char const* cpc = a;	// constant pointer to constant
cpc[2] = ‘r’;			// error: cpc points to constant
cpc = a;			// error: cpc is a constant pointer
}
...

In case of constant pointer, const* and *const are referred as the same. Some people find it helpful to read such declarations from right to left.

Char *const cp;		// constant pointer to char
Char const* pc;		// pointer to constant char
const char *pc;		// pointer to constant char
...

You can assign the address of a variable to a ‘pointer to constant’ because no harm can come from that. However, the address of a constant cannot be assigned to an unrestricted pointer because this would allow the object’s value to be changed. For example:

Int a = 1;		
const int c = 2;
const int* p1 = &a;		// ok
const int* p2 = &c;		// ok
Int* p3 = &c;			// error: initialization of int* with const int*
*p3 = 3;		        //try to change the value of c
...

It is possible to explicitly remove the restrictions on a pointer to const by explicit type conversion; I will explain that later in this post.

Constant Parameter Variable

By declaring function pointer argument const, the function is prohibited from modifying the object pointed to. Constant function arguments really matter when used with references and pointers.

Char* strcpy(char* dest, const char* src);	// cannot modify * src
...

Constant Member Function

int func () const;
...

The const after the argument list in the function declaration indicates that these functions do not modify the state of an object. In a non-const member function of class X, the type of this is X*, while in const member function, the type of this is const X* to prevent modification of the object itself. A const member function can be invoked for both const and non-const objects, whereas a non-const member function can be invoked only for non-const objects.

Constant Iterator

const iterators don’t allow you to change the values that they point to, while regular iterators do.

Constant Casting

Const_cast<>’ manipulates the constness of an object, either to be set or to be removed.

Mutable Keyword

mutable’ is a storage specifier. It specifies that a member should be stored in a way that allows updating- even when it is a member of a const object. In other words mutable means, “can never be const”.

mutable string cache;
...

Uses of Constant

Q. Can we overload constant member functions?

A. The answer to this is very well yes. We can overload const and non-const function. For example:

void func();
void func() const;
...

When we call func() using non-const object, the non-const member function is called and const object always prefers const member function.

Q. Can we override constant member functions? Can virtual functions be const?

A. Yes, we can override const member functions and so they can be virtual.

Q. Can we have const constructor and destructor of a class?

A. No. It gives compiler error C2583. 'const' 'this' pointer is illegal for constructors/destructors.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Rahul Warhekar from Pune, MH
Software Developer (Senior)
India India
No Biography provided

Comments and Discussions

 
Questionconst pointers Pinmembermithadis24-Mar-13 23:51 
QuestionInitializing a const array PinmemberManish K. Agarwal15-Mar-13 2:49 
AnswerRe: Initializing a const array PinmemberRahul Warhekar from Pune, MH18-Mar-13 3:28 
QuestionConstant constructors PinmemberMember 977325412-Mar-13 3:49 
AnswerRe: Constant constructors [modified] PinmemberRahul Warhekar from Pune, MH12-Mar-13 21:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141216.1 | Last Updated 12 Mar 2013
Article Copyright 2013 by Rahul Warhekar from Pune, MH
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid