[PLUG] a long involved question on const behavior of a C++ class object

logical american website.reader3 at gmail.com
Thu Oct 28 02:04:15 UTC 2010


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.

----------- start program main.cpp -----------
1 | #include <iostream>
2 | #include "ui256.hpp"
3 |
4 | using namespace std;
5 |
6 | int main()
7 | {
8 | const ui256 a(7);
9 | ui256 b(-7);
10 | unsigned int i = 8;
11 | int j = -6;
12 |
13 | cout << "a = " << a << endl;
14 | cout << "i = " << i << endl;
15 | cout << "j = " << j << endl;
16 | cout << endl;
17 | cout << "a + i = " << a << " + " << i << " = " << a+i << endl;
18 | cout << "a - j = " << a << " - " << j << " = " << a-j << endl;
19 | cout << "b + i = " << b << " + " << i << " = " << b+i << endl;
20 |
21 | return 0;
22 | }
----------------- end program -----------------
ui256.hpp and ui256.cpp contain the class ui256 and its methods.

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

If I change the operator to:

ui256 operator+(ui256& rhs);

then the compiler complains that

main.cpp:17: error: no match for ‘operator+’ in ‘a + i’

which is true, there isn't any function signature match to const a in 
this case.

So how is an operator+ for a const object defined?

For the subtraction in line #18, I wrote an outside the class operator 
and the compiler complains about ambiguity, since it is trying to coerce 
a native type to the class type then apply the class operator.

ui256.cpp: In function ‘ui256 operator-(const ui256&, int)’:
ui256.cpp:1632: warning: ISO C++ says that these are ambiguous, even 
though the worst conversion for the first is better than the worst 
conversion for the second:
ui256.cpp:1629: note: candidate 1: ui256 operator-(const ui256&, int)
ui256.hpp:127: note: candidate 2: ui256 ui256::operator-(const ui256&)

I just need some way of creating temporaries from constants which invoke 
non-const class methods without the compiler complaining about tossing 
aside the const when using it.

Any ideas of what I am doing wrong here and how to really fix the problem?

-Randall




More information about the PLUG mailing list