Code
#include <iostream>
class A
{
public:
mutable int x;
mutable int y;
A(int k1=0, int k2=0):x(k1), y(k2){}
void display()
{
std::cout<<x<<","<<y<<"\n";
}
};
int main()
{
const A a1;
a1.x=3;
a1.y=8;
a1.display();
return 0;
}
Output
Error: 'this' argument to member function 'display' has type 'const A', but function is not marked const
I am just calling member function A::display() through const qualified object const A a1 . So why line a1.display() is giving an error ?
CodePudding user response:
Why line
a1.display()is giving an error ?
The mutable variable let you modify the member variables inside a const qualified function.
It does not allow you to be able to call the non-const qualified member function to be called via a const qualified instance. Therefore, you need a const member function there.
