tags:

views:

71

answers:

4

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*/}
+4  A: 

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.

Hans Passant
Good answer. Trying to make the point even clearer: Since `func2` takes a `const C thus the required `const` in the declaration.
stakx
Drew
Hans Passant
+1  A: 

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
Timo Geusch
+1  A: 

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.

Michael Burr
A: 

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.

bits