Operator overloads work just like functions... just with more intuitive syntax.
For example, if you have a member function:
1 2 3 4 5
|
class MyClass
{
public:
MyClass& Assign(const MyClass& rhs);
};
|
You call the member function like this:
1 2 3
|
MyClass a, b;
a.Assign(b);
|
Overloading the assignment operator is the same thing... only instead of calling a "function", it calls the overload (which basically
is a function):
1 2 3 4 5 6
|
class MyClass
{
public:
// instead of an "Assign" function, just use the assignment operator
MyClass& operator = (const MyClass& rhs);
};
|
Then, you can "call" that operator by using the normal assignment operator:
1 2 3
|
MyClass a, b;
a = b; // calls the assignment operator
|
It's really that simple!
Most of the time, the assignment operator will just assign all of it's members over.
Here's an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class MyClass
{
private:
int foo;
int bar;
public:
MyClass& operator = (const MyClass& rhs)
{
foo = rhs.foo;
bar = rhs.bar;
return *this;
}
};
|
Pretty basic... it just assigns each member like you'd expect. This is what a properly functioning assignment operator would look like 99% of the time.
Now because it's so common, it would be really annoying if you had to do that for each class you wrote. So the compiler will automatically generate a "generic" assignment operator that does exactly what's illustrated above: it just goes through each member and assigns them.
Normally this works great. But sometimes it doesn't work so well... usually when you have pointers, or like in your case when you have a const member.
This is what was happening with you:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class MyClass
{
private:
const int foo;
int bar;
public:
// The compiler was auto-generating this "generic" assignment operator
// behind the scenes
MyClass& operator = (const MyClass& rhs)
{
foo = rhs.foo; // error, cannot assign foo because it's const!
bar = rhs.bar;
return *this;
}
};
|
This is why you were getting an error. The auto generated function was doing something illegal. So you had to get rid of it.
The auto-generated function is only generated if you do not specify your own assignment operator. So by declaring a "blank" one... that stops the compiler from auto-gen'ing the generic one, which avoids the const error. And by making it private (and not giving it a body), we ensure that it can never be called accidentally.