Wednesday, 28 October 2015

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;
}
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;
}


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;
}
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;
}
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above

No comments:

Post a Comment