πŸ“Š C++
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
πŸ’¬ Discuss
βœ… 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

Explanation by: Dharmendra Sir
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

πŸ’¬ Discussion


πŸ“Š Question Analytics

πŸ‘οΈ
200
Total Visits
πŸ“½οΈ
4 y ago
Published
πŸŽ–οΈ
Dharmendra Sir
Publisher
πŸ“ˆ
99%
Success Rate