Open In App

Output of C++ Program | Set 11

Last Updated : 27 Dec, 2016
Improve
Improve
Like Article
Like
Save
Share
Report

Predict the output of following C++ programs.

Question 1




#include<iostream>
using namespace std;
  
class Point
{
private:
    int x;
    int y;
public:
    Point(const Point&p) { x = p.x; y = p.y; }
    void setX(int i) {x = i;}
    void setY(int j) {y = j;}
    int getX() {return x;}
    int getY() {return y;}
    void print() { cout << "x = " << getX() << ", y = " << getY(); }
};
  
  
int main()
{
    Point p1;
    p1.setX(10);
    p1.setY(20);
    Point p2 = p1;
    p2.print();
    return 0;
}


Output: Compiler Error in first line of main(), i.e., “Point p1;”

Since there is a user defined constructor, compiler doesn’t create the default constructor (See this GFact). If we remove the copy constructor from class Point, the program works fine and prints the output as “x = 10, y = 20”



Question 2




#include<iostream>
using namespace std;
  
int main()
{
    int *ptr = new int(5);
    cout << *ptr;
    return 0;
}


Output: 5
The new operator can also initialize primitive data types. In the above program, the value at address ‘ptr ‘ is initialized as 5 using the new operator.



Question 3




#include <iostream>
using namespace std;
  
class Fraction
{
private:
    int den;
    int num;
public:
   void print() { cout << num << "/" << den; }
   Fraction() { num = 1; den = 1; }
   int &Den() { return den; }
   int &Num() { return num; }
};
  
int main()
{
   Fraction f1;
   f1.Num() = 7;
   f1.Den() = 9;
   f1.print();
   return 0;
}


Output: 7/9
The methods Num() and Den() return references to num and den respectively. Since references are returned, the returned values can be uses as an lvalue, and the private members den and num are modified. The program compiles and runs fine, but this kind of class design is strongly discouraged (See this). Returning reference to private variable allows users of the class to change private data directly which defeats the purpose of encapsulation.

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads