Hi,
  I have a very dumb basic query .. while overloading assignment operator what 
we do we check for self referentiality (if both are same or not) and if not , 
then we delete the pointer member variable and allocate memory for it again and 
assign value. (Please correct me if I am wrong) .. My query is , why do we need 
to delete the existing memory and again to allocate instead of using the 
existing one itself.
 
My example code:
 //--- file Person.h
. . .
class Person {
    private:
        char* _name;
        int   _id;
    public:
        Person& Person::operator=(const Person& p);
    . . .
}//--- file Person.cpp
. . .
//=================================================== operator=
Person& Person::operator=(const Person& p) {
    if (this != &p) {  // make sure not same object
        delete [] _name;                     // Delete old name's memory. // 
why do I need to do this? cant I use the exisitng memory itself?
        _name = new char[strlen(p._name)+1]; // Get new space
        strcpy(_name, p._name);              // Copy new name
        _id = p._id;                         // Copy id
    }
    return *this;    // Return ref for multiple assignment
}//end operator= Thx,--Gopi


      Add more friends to your messenger and enjoy! Go to 
http://messenger.yahoo.com/invite/

[Non-text portions of this message have been removed]

Reply via email to