Cannot convert 'this' pointer to class &

Can someone tell me why I get this error when compiling 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
source share
4 answers

The C :: func () method does not promise that it will not modify the object, but only promises that it will not change 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. It seems like this should be when object C is required as an argument.

+11
source

You need to mark C::func(const C &obj) as const, since you are calling it from a const object. The correct signature will look like this:

 void func(const C& obj) const 
+2
source

The problem is that in func2() you are calling the non-const ( C::func() ) function using the 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.

+1
source

Because:

 this 

is a const pointer to the current obj object.

Therefore, you can either make func as 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 pointer constant this as follows:

 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 this helps.

+1
source

Source: https://habr.com/ru/post/1315846/


All Articles