On 10/29/2010 5:03 PM, Daniel X. Pape wrote:
> logical american wrote:
>> Technical and long involved question here involving C++ class behavior,
>> please skip for non C++ gurus
>>
>> This is a question about invoking class methods from const class objects
>> without the compiler complaining about ignoring the const qualifier and
>> throwing an error.
> [...]
>> $ g++ -o main main.cpp ui256.cpp -ggdb
>> main.cpp: In function ‘int main()’:
>> main.cpp:17: error: passing ‘const ui256’ as ‘this’ argument of ‘ui256
>> ui256::operator+(const ui256&)’ discards qualifiers
>> main.cpp:18: error: passing ‘const ui256’ as ‘this’ argument of ‘ui256
>> ui256::operator-(const ui256&)’ discards qualifiers
>>
>> The operator + is defined as
>>
>> ui256 operator+(const ui256&  rhs);
>>
>> The compiler complains that the const ui256 a(7) object invoking the +
>> operator disregards the const since the operator is working on a
>> non-const class (temporary) which is true.
> [...]
>> Any ideas of what I am doing wrong here and how to really fix the problem?
> I think what is happening is not that your const ui256 a(7) object is
> disregarding the (argument's) const because of the non-const temporary
> (ui256(1)), but rather that you are attempting to call a non-const
> function (operator+) on your const object, a.
>
> I was able to make the errors go away in my version of g++
> (4.3.3-5ubuntu4) by changing your operator+ and operator- declarations to:
>
>      ui256 operator+(const ui256&  rhs) const;
>      ui256 operator-(const ui256&  rhs) const;
>
>
> What do you think?
>
> dan
>
> _______________________________________________
> PLUG mailing list
> [email protected]
> http://lists.pdxlinux.org/mailman/listinfo/plug
>
Dan:

This is correct. Adding the const at the end of the member function 
tells the compiler to go ahead and create the function if the promise to 
not change the parameters is met (and it is checked inside the member 
function anyways)

I found that the best solution was to move the mathematical operators (+ 
- * / % ) entirely outside the member methods, declare them as friends 
with binary input and return an object of that class.  This successfully 
gets around the const ( or no const) parameters.

I think the designers of C++ (Stroustrup) wanted to make things easy for 
the compiler, so we are forced to write all the operator overloads, not 
depend upon the compiler to get them correct for the class (not that 
this is possible anyways)

I do have C++ code running now, but invoking Boolean operators upon 
const class objects member functions is still something that I don't 
quite know how to do without creating a temporary or using a const_cast.

Thanks for your answer.

Randall

_______________________________________________
PLUG mailing list
[email protected]
http://lists.pdxlinux.org/mailman/listinfo/plug

Reply via email to