"CoolPint" <co******@yahoo .co.uk> wrote in message
news:15******** *************** ***@posting.goo gle.com...
It seems to me that I cannot assign objects of a class which has a
constant data member since the data member cannot be changed once the
constructor calls are completed. Is this the way it is meant to be? Am I
not suppose not to have any constant data member if I am going to have the
assignment operator working for the class?
Or am I missing something here and there is something I need to learn
about?
You mean, you have a class like this
class Foo
{
const int unchangeableVal ue;
int changeableValue ;
public:
Foo (int, int);
};
Foo::Foo (int value1, int value2) :
unchangeableVal ue(value1), changeableValue (value2)
{
}
and you're trying to do an assignment like this?
Foo foo1(1, 2);
Foo foo2(3, 4);
foo1 = foo2;
This is called "copy assignment," because both objects in the assignment are
of the same type. The default method used for copy assignment is called
"memberwise copy." In this method, each member of one object is simply
assigned to the corresponding member of the other object. So this statement
foo1 = foo2;
leads to code that assigns foo2.unchangeab leValue to foo1.unchangeab leValue,
and assigns foo2.changeable Value to foo1.changeable Value. The problem, of
course, is that you can't assign foo2.unchangeab leValue to
foo1.unchangeab leValue, because unchangeableVal ue is defined to be const.
One solution would be to define unchangeableVal ue to be non-const. But that
may not be what you want.
Another solution might be to define unchangeableVal ue as a static member of
Foo. Static members aren't involved in copy assignment. But the side
effect would be that every instance of Foo would have the same
unchangeableVal ue. This may or may not be acceptable to you.
Another solution would be to "overload" the copy assignment operator for
Foo. In other words, substitute your own copy-assignment operation for the
default memberwise-copy operation.
You overload the assignment operator by adding a new member function to Foo.
The name of this function is "operator=" :
class Foo
{
int const unchangeableVal ue;
int changeableValue ;
public:
Foo (int, int);
Foo &operator= (Foo const &);
};
// constructor
Foo::Foo (int value1, int value2) :
unchangeableVal ue(value1), changeableValue (value2)
{
}
// copy assignment
Foo &Foo::operat or= (Foo const &other)
{
// we're ignoring unchangeableVal ue
changeableValue = other.changeabl eValue;
return *this;
}
Now this statement
foo1 = foo2;
leads to this function call:
foo1.operator=( foo2);
Since operator= doesn't attempt to assign to unchangeableVal ue, it's legal.
Hope that helps. Let us know if you have further questions.
Regards,
Russell Hanneken
rh*******@pobox .com