A

Admin • 833K Points
Coach

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;
}
  • (A) 0
  • (B) Random value
  • (C) Compilation error
  • (D) None of these
  • Correct Answer - Option(C)
  • Views: 18
  • Filed under category C++
  • Hashtags:

Explanation by: Admin

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

You must be Logged in to update hint/solution

Discusssion

Login to discuss.

Be the first to start discuss.