Confusion of the "const" keyword

C++ ImageThe const keyword when used in different places can sometimes be confusing. When declaring a global constant as such:

const int TEN = 10; or int const TEN=10;

the const keyword is pretty straight forward, but when using it with functions or object methods it can be confusing at times. This article was great is clearing up my confusion with the use of the const keyword in functions and object methods. This is my little cheat-sheet:

const int * Constant2
declares that Constant2 is variable pointer to a [constant] integer and

int const * Constant2
is an alternative syntax which does the same, whereas

int * const Constant3
declares that Constant3 is constant pointer to a [variable] integer and

int const * const Constant4
declares that Constant4 is constant pointer to a constant integer.
Basically, [const applies to whatever is on its immediate left other than if there is nothing there in which case it applies to whatever is its immediate right]).

When a function has a parameber that is passed by reference it has
the ability to change or not change the actual variable. It is good
to use pass-by reference to save space when dealing with large data.
The problem is that the computer does not know when a variable will
be changed or if the function is just trying to save space and time
by not copying the variable over. This is where const comes in. If
the const keyword is used before the reference parameter then the
incoming variable is not copied (obviously) and the incoming variable
can not be changed. For example:

void Subroutine3(int const &Parameter1)
{ Parameter1=96; }

will cause the variable to be passed without copying, hence saving
space and also prevent the variable from then being accidently altered.
When using classes to prevent a non-parameter-having method from
chaning object variables, the const keyword may be placed after the
method like so:

class Class2 {
void Method1() const;
int MemberVariable1;

This will prevent Method1 in Class2 from altering any member
variables in the object.

This entry was posted in General-Tech. Bookmark the permalink.

One Response to Confusion of the "const" keyword

  1. Get your High School Diploma, Or any Desired College Degree, In less then 2 weeks.Call this number now 24 hours a day 7 days a week (413) 208-3069Get these Degrees NOW!!!High School Diploma “BA”, “BSc”, “MA”, “MSc”, “MBA”, “PHD”, Get everything within 2 weeks.100% verifiable, this is a real dealAct now you owe it to your future.(413) 208-3069 call now 24 hours a day, 7 days a week.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s