-1

I have a task to solve. I was given a main and need to expand class to do programs in main and on the console to be printed (-1, 1).

Given main:

int main() {
    point a(2, 1), b(-3);
    a.move(b).print();
}

and here is the code I wrote that is working:

#include <iostream>

using namespace std;

class point {
private:
    int x, y;
public:
    point(int x, int y) : x(x), y(y) {}
    point move(const point &p) {
        x += p.x;
        y += p.y;
        return *this;
    }
    void print() {
        cout << "(" << x << ", " << y << ")" << endl;
    }
};

int main() {
    point a(2, 1), b(-3, 0);
    a.move(b).print();
}

So here comes the question: As you see the b class in main should be just (-3), but in my code it doesnt work, it only works when it is (-3, 0). So i was wondering what to do so it can only stand (-3) in brackets.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Stuywesant
  • 39
  • 4
  • 1
    Did the person giving you this task teach default parameters? Did the person giving you this task teach how to write multiple constructors? There are several ways to construct an object from a single `int`. – Drew Dormann Jan 22 '23 at 16:06
  • How about `point(int x, int y) : x(x), y(42) {}` – Mike Nakis Jan 22 '23 at 16:06

1 Answers1

4

Just declare the constructor with default arguments as for example

explicit point(int x = 0, int y = 0) : x(x), y(y) {}

//...

point a(2, 1), b(-3);

Another approach is to overload the constructor as for example

point(int x, int y) : x(x), y(y) {}
explicit point( int x ) : point( x, 0 ) {}
explicit point() : point( 0, 0 ) {}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335