0

I have code for a Cartesian class and now I want to add a memberwise assignment to set the values of coord1 to coord2. I am not quite sure how to go about doing this. What is the syntax for writing a memberwise assignment for class objects? Would I make changes to the class itself, or put them in the main function?

#include <iostream>
using namespace std;

class Cartesian
{
private:
    double x;
    double y;

public:
    Cartesian( double a = 0, double b = 0) : x(a), y(b){}

    friend istream& operator>>(istream&, Cartesian&);
    friend ostream& operator<<(ostream&, const Cartesian&);
};

istream& operator>>(istream& in, Cartesian& num)
{
    cin >> num.x >> num.y;
    return in;
}

ostream& operator<<( ostream& out, const Cartesian& num)
{
    cout << "(" << num.x << ", " << num.y << ")" << endl;
    return out;
}

int main()
{
Cartesian   coord1, coord2;

    cout << "Please enter the first coordinates in the form x y" << endl;
    cin >> coord1;

    cout << "Please enter the second coordinates in the form x y" << endl;
    cin >> coord2;

    cout << coord1;
    cout << coord2;

    return 0;
}
user3427349
  • 3
  • 1
  • 3
  • You need to overload operator=. Please check this thread : http://stackoverflow.com/questions/4421706/operator-overloading and also the links mentioned in that thread. That should give you an overview. – MS Srikkanth Apr 06 '14 at 21:56
  • @user3493289 default (auto-generated) operator= is enough in this very case... – PiotrNycz Apr 06 '14 at 21:59
  • @PiotrNycz - Yes I know. I was just pointing him to links on how he can implement one. – MS Srikkanth Apr 06 '14 at 22:35

2 Answers2

2

Do it the simple way: Make all members public, by using a struct and leaving out access specifiers. Data hiding does not make sense if you provide full access anyway.

Also, you can then leave out all custom constructors, as you can assign all members at once without.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
1

Just add get and set methods to your class

void Cartesian::SetX(double new_x)
{
    x = new_x;
}

and

double Cartesian::GetX()
{
    return x;
}

and similar functions for GetY() and SetY(double y). This will enable you to access and set the values of x and y to whatever you want as and when you need.

Alternatively, simply change the access specifier on these members to public instead of private.

Also, be aware that your class has a default operator=() that will copy members memberwise if you assign one instance of Cartesian to another.

Thus if you have

 Cartesian point1(1.0,2.0);
 Cartesian point2(4.5,4.3);

you can simply assign point1 to point2 by

 point2 = point1;
mathematician1975
  • 21,161
  • 6
  • 59
  • 101