Notes about const in C++

This article contains some note about using const in c++;

Objective of using const

The main objective of using const is to:

Prevent changes to the data or Make it Read only

More Detail:

  • Prevent the caller change the values of a string in my class;
  • Prevent the caller change a constant value such as Pi, MaxOfPlayer, …
  • Better ownership of a piece of data, it is good to controlled the data by one source;

Use Cases and Sytnax

Make a value readonly

Syntax: 

const int value; 
int const value; 
const char *message = "Hello Cpp";

 

Usage:
It usually used to define constant such as Pi,  maximum value of somethings, .. ;

Make the content pointed by a pointer readonly

Syntax: 

const Point *getCurrentPosition(); // a method of an object;
const Point *point = anObject.getCurrentPosition();

Usage:
Prevent caller change any value of the object pointer;

Make the pointer address readonly

Syntax: 

Point *const originalPosition;

Usage:
Prevent the change of a pointer address so that the value is the same anywhere after first assignment;

Reference:

 

Advertisements

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