My class is not a modifiable lvalue?
I have a very simple class
class Point
{
public:
Point();
Point(double x, double y);
double x_;
double y_;
}
the problem is, I can't assign my class to another instance, ie:
Point A(2,4);
Point B();
B = A;
It says the lvalue must be modifiable. Why is it not?
Thanks,
Dave
daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
Try this.
class Point {
public:
double x;
double y;
Point() {
x = 0;
y = 0;
}
Point(double _x, double _y);
x = _x;
y = _y;
}
Point &operator =(const Point &p) {
x = p.x;
y = p.y;
return *this;
}
};
William Hemsworth
Posting Virtuoso
1,591 posts since Mar 2008
Reputation Points: 1,429
Solved Threads: 129
Point B(); is the declaration of a function called 'B' which takes no arguments and returns a Point.
modify to Point B ; and you have the definition of a variable called 'B' which is of type Point (initialized via the default constructor).
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
ahhh that was the key ! Needed to use B instead of B()
Thanks!
daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
Are you completely sure about this?
As far as i know if you have declared the Point class' constructor Point() and then you state Point B(); then B is an instance of Point instantiated via the default constructor.
I also thought that that if you declare the copy constructor the assignation B = A should propery work
class Point{
private:
int x_;
int y_;
public:
Point(){/* whatever*/}
Point(int x,int y){/* whatever*/}
Point(const Point& p){
x_ = p.x_;
y_ = p.y_;
}
};
I consider myself a begginer and I learn as I go. Then this you posted doesn't seems to be correct for me. Pleas correct me.
Kind regards
Yes, vijayan121 is correct. Try this program below and see what happens:
#include <iostream>
using namespace std;
class Point {
public:
double x;
double y;
Point()
{
cout << "I'm in the constructor\n";
x = 0;
y = 0;
}
Point(double _x, double _y)
{
x = _x;
y = _y;
}
Point &operator =(const Point &p)
{
x = p.x;
y = p.y;
return *this;
}
};
int main ()
{
Point B(); // nothing displayed
Point C; // constructor call
B(); // function call
Point D (); // nothing displayed
return 0;
}
Point B ()
{
cout << "I'm in the function\n";
Point* A = new Point (); // constructor call
return *A;
}
VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711