Skip to content
Related Articles

Related Articles

Improve Article
C++ | Constructors | Question 12
  • Last Updated : 03 Aug, 2013

Predict the output of following program.




#include<iostream>
using namespace std;
class Point {
    int x;
public:
    Point(int x) { this->x = x; }
    Point(const Point p) { x = p.x;}
    int getX() { return x; }
};
  
int main()
{
   Point p1(10);
   Point p2 = p1;
   cout << p2.getX();
   return 0;
}

(A) 10
(B) Compiler Error: p must be passed by reference
(C) Garbage value
(D) None of the above


Answer: (B)

Explanation: Objects must be passed by reference in copy constructors. Compiler checks for this and produces compiler error if not passed by reference.

The following program compiles fine and produces output as 10.

#include <iostream >
using namespace std;
class Point {
    int x;
public:
    Point(int x) { this->x = x; }
    Point(const Point &p) { x = p.x;}
    int getX() { return x; }
};

int main()
{
   Point p1(10);
   Point p2 = p1;
   cout << p2.getX();
   return 0;
}

The reason is simple, if we don’t pass by reference, then argument p1 will be copied to p. So there will be a copy constructor call to call the copy constructor, which is not possible.

Quiz of this Question

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.
My Personal Notes arrow_drop_up
Recommended Articles
Page :