Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert 'this' pointer to Class&

Tags:

c++

Can someone tell why i'm getting this error when compling this class?

class C
{
public:
    void func(const C &obj)
    {
       //body
    }

private:
    int x;
};

void func2(const C &obj)
{
    obj.func(obj);
}

int main() { /*no code here yet*/}
like image 557
Drew Avatar asked Dec 08 '22 02:12

Drew


1 Answers

The C::func() method doesn't promise that it won't modify the object, it only promises that it won't modify its argument. Fix:

   void func(const C &obj) const
    {
       // don't change any this members or the compiler complains
    }

Or make it a static function. Which sure sounds like it should be when it takes a C object as an argument.

like image 174
Hans Passant Avatar answered Dec 09 '22 16:12

Hans Passant