"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.