I am overloading the assignment operator for a class Arr. This is implemented by using the destructor to delete the old object (and release allocated memory), and then use the copy-constructor (which is previously overloaded) to make the calling object a copy of rhs. this picture shows two different ways to do this (only line 50 and 57 differ). Why do the second solution work, but not the first?
The error message is "type name is not allowed"
Arr& Arr::operator=(const Arr& rhs) {
this->~Arr();
this->Arr(rhs); // I get an error here: type name is not allowed
return (*this);
}
Arr& Arr::operator=(const Arr& rhs) {
this->~Arr();
this->Arr::Arr(rhs);
return (*this);
}
I know it is possible to use copy-and-swap, but still: what goes wrong here?
Well, in GCC both are not allowed. My guess is that if your compiler allows one but not the other, then it is to avoid disambiguation.
When you write this->Arr()
, the compiler cannot know that you meant to call the constructor, rather than just instantiate a new object.
When you write this->Arr::Arr()
, then the compiler knows that you call the static function Arr()
of the class Arr
.