C++: Two ways to build a point

Give a class two constructors, and choose between them for each command.

What to build

A Point class with a default constructor and a constructor that takes coordinates.

Requirements

  • Keep x and y private.
  • Write Point(), which starts at (0, 0), and Point(int x, int y).
  • Use a member initializer list in both.
  • Write a const print member function that prints (x, y).

Input

The first line has q. Each of the next q lines is default, or at x y.

Output

One line per command: the point that was built.

Constraints

1 ≤ q ≤ 100, and the coordinates are from -1000 to 1000.

Example

Input:

3
default
at 3 4
at -1 2

Output:

(0, 0)
(3, 4)
(-1, 2)

Why it works

Constructors are overloaded like any functions, so the compiler runs the one that matches the arguments. Either way, the object is fully set up as it is created.

Examples

Example 1 · Input
3
default
at 3 4
at -1 2
Expected output
(0, 0)
(3, 4)
(-1, 2)
Example 2 · Input
1
default
Expected output
(0, 0)

Hints

Hint 1

A default constructor takes no arguments: `Point() : x(0), y(0) {}`.

Hint 2

A second constructor takes the coordinates: `Point(int x, int y) : x(x), y(y) {}`.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;

class Point {
    int x, y;
public:
    Point() : x(0), y(0) {}
    Point(int x, int y) : x(x), y(y) {}
    void print() const {
        cout << "(" << x << ", " << y << ")" << endl;
    }
};

int main() {
    int q;
    cin >> q;
    while (q-- > 0) {
        string word;
        cin >> word;
        if (word == "default") {
            Point p;
            p.print();
        } else {
            int x, y;
            cin >> x >> y;
            Point p(x, y);
            p.print();
        }
    }
    return 0;
}

Lesson: Constructors and destructors →