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

Daniel X. Pape dpape at dpape.com
Sat Oct 30 00:03:22 UTC 2010


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




More information about the PLUG mailing list