[LC++]How to use const member functions correctly?

Dan hursh hursh at sparc.isl.net
Sat Sep 22 00:44:04 UTC 2001


   If I understand you correctly, you are say you have a const member
function for an object.  It takes a non-const reference as an argument.
You want to know if there is something wrong with it modifying the
argument, but not the 'this' object.

	const myobj a;
	myobj b;

	a::constf(myobj& v) const;
	a.constf(b);  // modifies b.  valid and good

You want to know what happens here

	const myobj a, b;

	a::constf(myobj& v) const;
	a.constf(b);  // error, can't pass a const to a non-const function

The above will/should bomb on compile.  constf expects it argument to be a
non-const reference, which b is not.  The const declaration for a method
is only a promise that the 'this' object will not be altered (aside from
mutable members).  In order to say it won't change the arguments you have
to declare the arguments as const.  This is totally separate from the
method being const.

	const myobj a, b;

        a::constf(const myobj& v) const;
        a.constf(b);  // a & b don't change, happy happy joy joy



On Fri, 21 Sep 2001, Mark Phillips wrote:

> Things have been a bit quiet on this list of late.  Time
> to ask a question!
> 
> My understanding of const member functions, is that by declaring
> it constant, you are giving a guarentee that it will not change
> the internals of the object.
> 
> But I have a problem.  What if I have a member function which has
> a parameter passed by reference (non-constant).  Passing by
> reference allows the function to modify an external variable.
> Normally this external variable will be unrelated to the internals
> of the object, so for most of the time, this function may be thought
> of as const.  But what if somewhere, this function is used to modify
> an internal variable of the object --- by passing it in as the
> reference parameter --- then all of a sudden the function is non-const!
> 
> What should be done in this situation?  Should I declare it const, and
> rely on the programmer to take care not to pass in the wrong parameter?
> 
> If I don't make it const, then I can't call the function from other
> const member functions, even though I know that in this case it is
> not changing internals.
> 
> What to do??
> 
> Thanks,
> 
> Mark.
> _______________________________________________
> This is the Linux C++ Programming List
> : http://lists.linux.org.au/listinfo/tuxcpprogramming List
> 




More information about the tuxCPProgramming mailing list