Drew
Drew

Reputation: 43

Cannot convert 'this' pointer to Class&

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*/}

Upvotes: 4

Views: 6795

Answers (4)

Hans Passant
Hans Passant

Reputation: 941525

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.

Upvotes: 11

bits
bits

Reputation: 8340

Because:

this

is a const pointer to current obj.

Therefore you can either make the func to be const:

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

private:
    int x;
};

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

int main() { 
return 0;
}

OR

you can remove the constness of the this pointer like this:

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

private:
    int x;
};

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

int main() { 
return 0;
}

Hope that helps.

Upvotes: 1

Michael Burr
Michael Burr

Reputation: 340218

The problem is that in func2() you're calling a non-const function (C::func()) using a const object.

Change the signature of C::func() to:

void func(const C &obj) const
{
    // whatever...
}

so that it can be called with const objects.

Upvotes: 1

Timo Geusch
Timo Geusch

Reputation: 24351

You need to mark C::func(const C &obj) as const as you're calling it from a const object. The correct signature would look like this:

void func(const C& obj) const

Upvotes: 2

Related Questions