cannot convert 'this' pointer from 'const myClass' to 'myClass &'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

using namespace std;

class myClass
{
public:
	int myInt;
	myClass() { myInt = 111; }

      //cannot convert 'this' pointer from 'const myClass' to 'myClass &'
      //myClass myFunc01(myClass const & mc1, myClass mc2) {
	myClass myFunc01(myClass const & mc1, myClass mc2) const {
		mc2.myInt++;
		return mc2;
	}
};

int main()
{
	
	const myClass mc1;
	myClass mc2;
	mc2.myInt = 222;

	printf("before: myInt(%d) myInt2(%d)\n", mc1.myInt, mc2.myInt);
	mc2 = mc1.myFunc01(mc1, mc2);
	printf("after:  myInt(%d) myInt2(%d)\n", mc1.myInt, mc2.myInt);

	return 0;
}

Why do I get an error on line 27 (cannot convert 'this' pointer from 'const myClass' to 'myClass &') if I leave out the 'const' qualifier for myFunc01. The function is returning mc2, not mc1, so there is no danger of exposing the const mc1 parameter to changes through a return value. And even if the function did return mc1, it would be a copy only, not a reference since myFunc01's return type is 'myClass', not 'myClass &'. So I don't understand why the compiler requires myFunc01 to be const.

This does not display an error for me when using mingw or msvc compilers.
This is const correctness.

1
2
3
4
5
6
7
8
9
10
11
12
13
const myClass mc1;
// because mc1 is const, you cannot do things which might change its state
//  this includes writing to its members, and calling non-const member functions
//  (since non-const member functions are permitted to change members)

mc1.myFunc01( x, y );  //  this will fail unless myFunc01 is a const member function
   // because mc1 is const

// on the other hand, since mc2 is nonconst
myClass mc2;

// a non-const object can call const and non-const member functions just fine
mc2.myFunc01( x, y );  // no problem! 


That's why you need the const qualifier for the function.
Ah, I see, he meant the code line that he commented out.
Thanks Disch. Suddenly it seems obvious now that you put it that way. I was overthinking it, but I see now what you mean. So the compiler doesn't have time to check if the function actually changes any data members, it just sees that the function is not const, so therefore the function COULD change data members, therefore that is too dangerous and an error. Thanks Disch and thanks guestgulkan, sorry guestgulkan I was not more clear on how to duplicate the error.
Topic archived. No new replies allowed.