Why is it that get_controlState2
is fine being const but get_controlState
gives error passing 'const Main' as 'this' argument discards qualifiers
?
#include <iostream>
class Main {
public:
int getData() { return 123; } // Actually returns a mutable object
int get_controlState() const {
return this->getData(); // Error
}
};
class Controller {
public:
Controller(Main* pMain) : pMain{pMain} { }
int get_controlState2() const {
return pMain->getData(); // Fine
}
private:
Main* pMain;
};
int main() {
Main main;
Controller controller{&main};
std::cout << main.get_controlState() << std::endl;
std::cout << controller.get_controlState2() << std::endl;
return 0;
}
https://www.mycompiler.io/view/5xousuHcDdN
This is very similar to calling non-const function on non-const member in const function, but not exact. He has a library function that could be const but isn't because they cannot change it. In my case it returns a mutable object which is only read out, but works in some circumstances
His question is answered with "in a const function all members are const too", but this seems to contradict get_controlState2
.
What I'm trying to do is remove the delegate from Controller and put the function in Main instead.