C++ | Constructors | Question 8

#include <iostream>
using namespace std;

class Point
{
    int x, y;
public:
   Point(int i = 0, int j = 0) { x = i; y = j; }
   int getX() { return x; }
   int getY() { return y; }
};

int main()
{
    Point p1;
    Point p2 = p1;
    cout << "x = " << p2.getX() << " y = " << p2.getY();
    return 0;
}

(A) Compiler Error
(B) x = 0 y = 0
(C) x = garbage value y = garbage value


Answer: (B)

Explanation: Compiler creates a copy constructor if we don’t write our own. Compiler writes it even if we have written other constructors in class. So the above program works fine. Since we have default arguments, the values assigned to x and y are 0 and 0.

Quiz of this Question






Practice Tags :

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.