opMul

Bill Baxter dnewsgroup at billbaxter.com
Mon Mar 3 12:56:57 PST 2008


Denton Cockburn wrote:
> On Mon, 03 Mar 2008 15:08:55 +0100, Simen Kjaeraas wrote:
> 
>> On Mon, 03 Mar 2008 04:10:36 +0100, Denton Cockburn <diboss at hotmail.com>  
>> wrote:
>>> A function does not have to be constant to allow a constant parameter.
>>> It just has to promise not to change the parameter.
>> And that is exactly what const does.
>>
>>> I don't understand why opMul would change the parameter, or more
>>> importantly, why it can't be stated that it WONT change the parameter in
>>> any cases.
>> Given
>>
>> struct Foo
>> {
>> 	int bar;
>> 	void doStuff(Foo b)
>> 	{
>> 		bar += b.bar;
>> 	}
>> }
>>
>> would you expect
>>
>> const Foo f,g;
>> f.doStuff(g);
>>
>> to work without problems? This is exactly the same, only doStuff is not  
>> considered special by the compiler.
>>
>> You might argue that the compiler should enforce opMul, opDiv, etc. to be  
>> const, but that does carry a load of other troubles with it.
>>
>>> I think this is related to what Janice spoke about.  The constant changes
>>> that have taken place need to be properly incorporated into the language
>>> and library.  There are a lot of places where constant doesn't work as
>>> would be intuitively expected.
>> This is intuitive to me. (Well, apart from what I mentioned in the  
>> response to Bill :p)
> 
> You are unfortunately completely missing my point.
> In the example you give, you don't want a const parameter, because you
> change the object.
> 
> I WANT a const parameter, because I have NO INTENTION of changing the
> parameter.
> 
> so what I want is this:
> 
> struct Foo
>  {
>  	int bar;
>  	void doStuff(const Foo b)
>  	{
>  		bar += b.bar; /* I want an error here */
>  	}

You're not changing b, so you're not going to get an error there.

> 	/* now more specifically, I want to do the same as above...but with */
> 	/* opMul */
> 
> 	Foo opMul(const Foo b)
> 	{
> 		Foo res;
> 		res.bar = bar * b.bar;
> 
> 		return res;
> 	}
>  }
> 
> See, I make NO changes to the object in that opMul, so my question
> is...why is that illegal (intuitively)?

Your question is contradictory.  Above you say you want an error, but 
then ask why is that illegal.  It's not illegal.  It works fine.  Did 
you mean "why is it *legal*?"

If you mean why is it *legal* to use a const parameter like that, the 
answer is because const only says you won't change the parameter. 
Merely accessing a value does not change it.

--bb



More information about the Digitalmars-d mailing list