Q. What is the output of the following C++ code?
Code:
#include<iostream>
using namespace std;
class MyClass {
int val;
public:
MyClass (int v = 0) {val = v;}
int getValue() { return val; }
};
int main() {
const MyClass obj;
cout << obj.getValue();
return 0;
}
β
Correct Answer: (C)
Compilation error
Explanation: const object cannot call a non-const function. The above code can be fixed either by making getValue() const or by making obj non-const.
We can correct the code by adding “const” to getValue() as follows:
#include<iostream>
using namespace std;
class MyClass {
int val;
public:
MyClass (int v = 0) {val = v;}
int getValue() { return val; }
};
int main() {
const MyClass obj;
cout << obj.getValue();
return 0;
}
Then the code displays: 0