Const in C++

The const is used to define a readable variable or object, which can not be modified. It has the following effect:

1.  To define a constant, similar like define:

const int a=3;

int const a=3;

2. Applied to pointer:

Remember:

const is on the left of  *, then the content is constant;

const is on the right of *, then the pointer itself is constant.

1) The content is constant:

const int* p;

int const* p;

When a variable is const, its address can only be assigned to const pointer.

Example:

const int a;

const int* p=&a; //correct.

int* q=&a;//wrong.

2) The pointer itself is constant:

int* const p;

3) Both the content and the pointer are constant:

const int* const p;

3. Save memory

const int max=100;

4. To decorate function parameters:

void function(const int Var);  // Var remains constant inside function

void function(const char* Var); //The content of char* Var is constant inside function.

void function(char* const Var); //The pointer Var is constant inside function.

void function(const TYPE& Var); //The content referenced by Var remains constant.

Note that, the constant TYPE& Var transfers the address instead of the content. When the Type is complicated and large, it is more efficient than transferring the value, since it does not need copy operation. However, similar to  transferring by value, the const guarantees that Var remains the same.

5. When applied to class variable and functions:

1) const member variable

class A
{

const int nValue;  //constant variable member

A(int x): nValue(x) { } ; //constant variable member can only be initialized with initialization list.
}

2)const member function

class A
{

void function() const; //const function which can not modify any variable member.

}

3)const object

class AAA
{
void func1();
void func2() const;
}
const AAA aObj;
aObj.func1();  //wrong, since aObj is a const object, which can only invoke const function.
aObj.func2();  //correct

const AAA* aObj = new AAA();
aObj-> func1(); //wrong, since aObj point to a const object, which can only invoke const function.
aObj-> func2(); //correct.

Advertisements
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s