Output of C++ Program | Set 6

Predict the output of below C++ programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

#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


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

#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




Question 2

filter_none

edit
close

play_arrow

link
brightness_4
code

   
#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


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”.

filter_none

edit
close

play_arrow

link
brightness_4
code

#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


Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.