Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fixing my point class with x and y ints, so it can pass just (x) instead of (x, y)

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

>Solution :

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 ) {}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading