469,322 Members | 1,153 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,322 developers. It's quick & easy.

Why should we use fun(const Class &B) instead of fun(Class &B)?

Why should we use fun(const Class &B) instead of fun(Class &B)?

Aug 24 '07 #1
2 1538
"dolphin" <jd*******@gmail.comwrote in message
news:11**********************@e9g2000prf.googlegro ups.com...
Why should we use fun(const Class &B) instead of fun(Class &B)?
fun( const Class& B ) can accept a constant, or non constant instant of
Class, wereas fun( Class &B ) can only accept a non constant.

Consider a library I use where a certain function is declared similar to:

output( int x, int y, char * c )

Seems reasonable, right? Although output does not change the pointer
pointed to in the variable c. And since I normally use std::strings to do
output, I would like to do:

output( 10, 20, MyString.c_str() );
however, that fails. Why? Because c_str() returns a const char *, and that
can not be accepted by a function taking a non constant. So I have to
const_cast it, a real pain:

output( 10, 20,const_cast<char*>( MyString.c_str() ) );

Now consider your fun. Can you think of any possible time someone may want
to pass it a const Class? But they won't be able to without const casting
it, but then since it's not declared const, they won't be sure if fun is
modifying the instant of Class.

const correctness is a good thing. If you're not going to change a
parameter, it should be declared const.
Aug 24 '07 #2
On Aug 24, 8:12 am, dolphin <jdxyw2...@gmail.comwrote:
Why should we use fun(const Class &B) instead of fun(Class &B)?
1. gives the guarantee that B will not be changed (because you can
only call const member functions)
2. can be called on non-modifiable lvalues (Eg const objects,
temporaries, and for POD's - literals.)

-N

Aug 24 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Rafal 'Raf256' Maj | last post: by
6 posts views Thread by p|OtrEk | last post: by
46 posts views Thread by Herrcho | last post: by
4 posts views Thread by jayesah | last post: by
6 posts views Thread by CompGeek | last post: by
6 posts views Thread by alan | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by Gurmeet2796 | last post: by
reply views Thread by mdpf | last post: by
reply views Thread by harlem98 | last post: by
reply views Thread by listenups61195 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.