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

J

Jim Langston

dolphin said:
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.
 
N

Neelesh Bodas

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
 
J

Jorgen Grahn

1. gives the guarantee that B will not be changed (because you can
only call const member functions)

Nitpick: the object that B refers to will not be changed through B.
It can be changed through other, non-const, references and pointers.
2. can be called on non-modifiable lvalues (Eg const objects,
temporaries, and for POD's - literals.)

3. Documentation.
Because fun(Class& b) only offers you one thing which fun(const Class& b)
doesn't -- passing results from fun() by modifying b -- readers will
assume that fun(Class& b) does indeed do that.

/Jorgen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top