What happens when a const object attempts to call a non-const member function in C++?
#include <iostream>
using namespace std;
class Test {
public:
void show() {
cout << "Hello";
}
};
int main() {
const Test obj;
obj.show();
return 0;
}
Options
-
A.
It prints Hello
-
B.
It always prints nothing
-
C.
A compilation error occurs
-
D.
More than one of the above
-
E.
None of the above
Correct Answer (Detailed Explanation is Below)
C.
A compilation error occurs
Detailed Explanation
Correct Answer: Option CExplanation:show() is a non-const member function. A const object cannot call a non-const member function because that function is not guaranteed to preserve the object's constness. The program therefore fails to compile.