"Dominique" <NODOTd.b.g.e.n.e.r.a.l.0.1.LOSEDOTS@cogecoDOTca > wrote in
message news:Yn*******************@read1.cgocable.net...
Hi
Can anyone help here. I have defined a copy constructor:
CString::CString (const CString &string) // copy constructor
{
Int16 size = string.GetLength() + 1; // this line generates error
In this context, the object 'string' is const.
...
}
and the GetLength member:
Int16 CString::GetLength()
{
...
In this context, the 'CString' object (*this) is not const.
}
The error on the marked line is:
const CString as 'this' argument of 'Int16 CString::GetLength()' discards
qualifiers
It's essentially telling you that you're passing a const
object ('string') to a nonconst member function, which will
treat it (via the nonconst '*this') as a nonconst object,
by 'discarding the const qualifier'. You have just thrown
away the protection against inadvertent modification which
the copy ctor argument type originally provided.
I am using the GCC compiler, and I assume the 'const' is the source of the
problem, but everywhere I look, the copy constructor seems to be defined
correctly.
That's not where the problem is. :-)
Is this a problem in the compiler, or have I made an error?
You need to define 'GetLength()' as a const member function:
Int16 CString::GetLength() const
{
/* etc */
};
And don't forget to change the prototype to match.
*Any* member function which does not modify the object
(such as such 'get data' functions) should be defined
as const.
When I first came to C++, I found these 'const' issues
to be somewhat confusing and 'annoying', but quickly
came to see them for the lifesavers they really are. :-)
HTH,
-Mike