I'm writing an explicit assignment method, i find a big block of codes are same as copy constructor, I tried to call the copy constructor, but failed, why?
Can't constructors be called after the very first time when the object created?
Constructors are used when creating an object and should not be called on existing objects. Instead do it the other way around. Use the copy assignment operator in the copy constructor.
I'm writing an explicit assignment method, i find a big block of codes are same as copy constructor, I tried to call the copy constructor, but failed, why?
Sounds like you may benefit from copy-and-swap assignment idiom:
1 2 3 4 5 6 7 8 9
A& A::operator=(A other)
{
std::swap(member, other.member);
std::swap(member2, other.member2);
std::swap(member3, other.member3);
// swap every data member. Many people prefer making
// .swap() a member function to simplify this
return *this;
}
Note that this assignment operator takes its argument by value: that pass by value is what calls A's copy constructor.