CPB Mailing List

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Warning - non-const function



>How do I define binary class operators to make it clear that both
>parameters are const?
>
>Making the second parameter constant I can do. Making the 'this' object
>const for this operation is what I'm looking for. Where do I put the
>'const' keyword?
>
>// This doesn't seem to work.
>
>class MyClass
>{
>public:
>MyClass const operator+(const MyClass& one) ;
>};


Expanding slightly on your example:

class MyClass
{
   int x;
public:
   MyClass(int x):x(x) {}
   MyClass const operator+(const MyClass& one); // non-const version
   MyClass const operator+(const MyClass& one) const; // const version
};
MyClass const MyClass::operator+(const MyClass& one)
{
   return MyClass(x + one.x);
}
MyClass const MyClass::operator+(const MyClass& one) const
{
   return MyClass(x + one.x);
}


Example:

   const MyClass c(10);
   MyClass x(1);
   MyClass y(0);

   y = x + c; // non-const version of operator+ called
   y = c + x; // const version of operator+ called


This is so the compiler can guarantee constness, once constness is declared...

HTH,
Ken


W Komornicki's Home Page | Main Index | Thread Index