There is an exercise I'm having trouble with in Teach Yourself C++
in 21 days.
It says this:
Provide an operator= for SimpleCircle.
And gives this answer:
Why is the author calling delete on 'itsRadius' only to re-allocateCode:class SimpleCircle{ public: //.. SimpleCircle &operator=(const SimpleCircle &rhs); //.. private: int *itsRadius; } SimpleCircle &SimpleCircle::operator=(const SimpleCircle &rhs){ if(this == &rhs) return *this; delete itsRadius; itsRadius = new int; *itsRadius = rhs.GetRadius(); return *this; }
memory on the next line? The memory was originally allocated
in the constructor. Can't I still use that?
I didn't have the delete-call in my answer (below)... Why would
I need it? If I'm assigning a value to another variable, wouldn't
I only need to change the value that's at the already-allocated
memory?
It's on page 805, Question 7 (if anybody has the book)...Code:SimpleCircle &SimpleCircle::operator=(const SimpleCircle &rhs){ if(this == &rhs) return *this; *itsRadius = rhs.GetRadius(); return *this; }
-![]()



LinkBack URL
About LinkBacks




