Uses of "const"
I''m just getting to grips properly with c++ and I am a little curious about the uses of the "const" keyword. I would like to know what it means in the following situations:
void foo(const char& var)
and
int bar(char *var) const
Can anyone help?
Thanks in advance
Jx
In the first instance, the function cannot modify the parameter, and in the second instance (valid as a member function), the function cannot modify the member data.
You can think of it as making the data pointer points at read-only (the character pointer (ok, reference, same diff) in the first case, "this" in the second).
This helps the optimizer out some, as it can assume data will not be changed by the function call. It can also help prevent silly bugs or unexpected side-effects.
This helps the optimizer out some, as it can assume data will not be changed by the function call. It can also help prevent silly bugs or unexpected side-effects.
So the second useage should be used for "get" methods?
i.e.
int getInt( ) const
{
...
}
because we should not modify anything in there?
i.e.
int getInt( ) const
{
...
}
because we should not modify anything in there?
Const in many ways is also simply to indicate to the programmer "Don't expect your value to change in here." Same if you pass a pointer... typically that means "This will change." It's good programming practice to use const whenever you do not plan to change a parameter... that way, everyone is crystal clear.
Here's from MSDN:
"You call him Dr. Grip, doll!"
Edited by - the_grip on August 15, 2001 9:55:46 AM
Here's from MSDN:
|
"You call him Dr. Grip, doll!"
Edited by - the_grip on August 15, 2001 9:55:46 AM
"You call him Dr. Grip, doll!"
quote:
Original post by the_grip
Const in many ways is also simply to indicate to the programmer "Don''t expect your value to change in here."
Don''t know about you, but my compiler enforces constness to be applied to anything declared const.
You declare references const whenever possible, since you usually pass by reference for effeciency''s sake - if you want to change the value, you can use a reference or a pointer, but bear in mind that if you use a reference your maintenance programmer will hate you

--
Games, Anime and more at GKWorld
Meet Bunny luv'' and the girls, ready to perform on your desktop just for you (warning: adult content).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement