Newbie question about const keyword...
Hi all,
I just wanted to ask what the const at the beginning of the following function signifies:
const short get_age() const;
I know the const at the end effectively makes the function read-only so that it can't change the object/variable it returns (in this case age), but what does the other const mean?
Thanks in advance for your help.
[381 byte] By [
inert] at [2007-11-11 7:21:29]

# 3 Re: Newbie question about const keyword...
it refers to the return value of the function. BTW, this is bad programming practice and typically indicates some level of C++ ignorance. const should only be used when the return value is a pointer or reference.
Danny at 2007-11-11 21:04:29 >

# 4 Re: Newbie question about const keyword...
Ah I see, thanks for that.
Also, from:
That the "short" value you are returning is const
does this mean that when you declare the short (say as a member variable), that it must be declared as a const short, or does this convert it to a const when it returns it?
Thanks
inert at 2007-11-11 21:05:23 >

# 5 Re: Newbie question about const keyword...
It means the caller cannot modify the return value. You will want to put it into a constant value to avoid warnings or errors:
const short result = foo(); //whatever the function was.
if you just do
short result = foo();
you will get warnings or errors (I dunno, I have never done this to myself and forget trivial rules on stuff you shouldnt do in the first place).
jonnin at 2007-11-11 21:06:29 >

# 6 Re: Newbie question about const keyword...
the data member itself needn't be const. The const applies to the return value, which is anyway a *copy* of the data meber so you're forcing the caller to use a const short to store the result, which is useless and annoying since the caller uses its own short to which a copy is written -- not the object's data member. So other than complicating the design and annoying the users, this practice has no real benefits. In short (no pun intended), always return value object as non-const.
Danny at 2007-11-11 21:07:33 >

# 7 Re: Newbie question about const keyword...
Thats excellent guys, cleared that up nicely - cheers.
inert at 2007-11-11 21:08:26 >
