C++ | Constructors | Question 12

Predict the output of following program.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


(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



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


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