Output of C++ Program | Set 6
Predict the output of below C++ programs.
Question 1
#include<iostream> using namespace std; class Test { int value; public: Test (int v = 0) {value = v;} int getValue() { return value; } }; int main() { const Test t; cout << t.getValue(); return 0; } |
chevron_right
filter_none
Output: Compiler Error.
A const object cannot call a non-const function. The above code can be fixed by either making getValue() const or making t non-const. Following is modified program with getValue() as const, it works fine and prints 0.
#include<iostream> using namespace std; class Test { int value; public: Test (int v = 0) { value = v; } int getValue() const { return value; } }; int main() { const Test t; cout << t.getValue(); return 0; } |
chevron_right
filter_none
Question 2
#include<iostream> using namespace std; class Test { int &t; public: Test (int &x;) { t = x; } int getT() { return t; } }; int main() { int x = 20; Test t1(x); cout << t1.getT() << " "; x = 30; cout << t1.getT() << endl; return 0; } |
chevron_right
filter_none
Output: Compiler Error
Since t is a reference in Test, it must be initialized using Initializer List. Following is the modified program. It works and prints “20 30”.
#include<iostream> using namespace std; class Test { int &t; public: Test (int &x;):t(x) { } int getT() { return t; } }; int main() { int x = 20; Test t1(x); cout << t1.getT() << " "; x = 30; cout << t1.getT() << endl; return 0; } |
chevron_right
filter_none
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above
Recommended Posts:
- Output of C++ Program | Set 19
- Output of C program | Set 25
- Output of C Program | Set 24
- Output of C Program | Set 23
- Output of C++ Program | Set 10
- Output of C Program | Set 22
- Output of C++ Program | Set 8
- Output of C++ Program | Set 9
- Output of C++ Program | Set 7
- Output of C Program | Set 21
- Output of C Program | Set 26
- Output of C Program | Set 28
- Output of C++ Program | Set 11
- Output of C++ Program | Set 4
- Output of C Program | Set 29



