copy constructor V/s assignment operator

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vermarajeev
    New Member
    • Aug 2006
    • 180

    copy constructor V/s assignment operator

    Hi guys,
    I know what a copy constructor and an assignment operator is.
    I have read that in a copy constructor, deep copy () happens and in assignment operator shallow copy happens. My question is how?

    NOTE:
    deep copy-->implies duplicating an object
    shallow copy--> is a reference copy, i.e. just a pointer to a shared data block

    Code:
    class MyObject 
    {
    public:
      MyObject();      // Default constructor
      MyObject(MyObject const & a);  // Copy constructor ( copying happens by deep copy)
      MyObject & operator = (MyObject const & a) // Assignment operator (copying happens by shallow copy)
    }
    Can someone please make me understand how actually the copying happens in both copy constructor and an assignment operator

    Thanks
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Originally posted by vermarajeev
    Hi guys,
    I know what a copy constructor and an assignment operator is.
    I have read that in a copy constructor, deep copy () happens and in assignment operator shallow copy happens. My question is how?

    NOTE:
    deep copy-->implies duplicating an object
    shallow copy--> is a reference copy, i.e. just a pointer to a shared data block

    Code:
    class MyObject 
    {
    public:
      MyObject();      // Default constructor
      MyObject(MyObject const & a);  // Copy constructor ( copying happens by deep copy)
      MyObject & operator = (MyObject const & a) // Assignment operator (copying happens by shallow copy)
    }
    Can someone please make me understand how actually the copying happens in both copy constructor and an assignment operator

    Thanks
    The shallow copy/deep copy problem happens if u have a pointer member in the class.
    As u copy one iobject to another then the same pointer address is hared between the objects due to which the shallow copy problem happens.
    Thats why we go for our own implementaion of copy-constructor and assignment operator

    Raghuram

    Comment

    • vermarajeev
      New Member
      • Aug 2006
      • 180

      #3
      I think this is more clearer,
      Code:
      class A
      {
         char* m_name;
         public:
               A(){ m_name = 0; }
               A(const char* n)
               {
                    m_name = new char[strlen(n)+1];
                    strcpy(m_name,n);
               }
      		 /*A& operator = (const A& obj)
      		 {
      			if( this != &obj )
      			{
      				setData(obj.m_name);
      			}
      			return *this;
      		 }*/
               void setData(const char* n)
               {
                   if( m_name ) 
                      { 
                           delete m_name;
                           m_name = 0;
                      }
                    m_name = new char[strlen(n)+1];
                    strcpy(m_name,n);
               }
              void displayData()
              {
      			if( m_name )
                    cout<<"Name:"<<m_name<<endl;
              } 
      };
      int main()
      {
            A a1;
            a1.setData( "HELLO" );
            a1.displayData();
      
            A a2;
            a2.setData( "WORLD" );
            a2.displayData();
      
            a2 = a1;
            cout<<"After =:"<<endl;
            a1.displayData();
            a2.displayData();
            
            a1.setData( "FANTASTIC" );
      
            a1.displayData();
            a2.displayData();    
            return 0;
      }
      Run the code, see the output.
      Uncomment the assignment operator and then again run the code, see the output. This is the power of C++.
      Thanks my funda is now cleared.

      Comment

      • gpraghuram
        Recognized Expert Top Contributor
        • Mar 2007
        • 1275

        #4
        Originally posted by vermarajeev
        I think this is more clearer,
        Code:
        class A
        {
           char* m_name;
           public:
                 A(){ m_name = 0; }
                 A(const char* n)
                 {
                      m_name = new char[strlen(n)+1];
                      strcpy(m_name,n);
                 }
        		 /*A& operator = (const A& obj)
        		 {
        			if( this != &obj )
        			{
        				setData(obj.m_name);
        			}
        			return *this;
        		 }*/
                 void setData(const char* n)
                 {
                     if( m_name ) 
                        { 
                             delete m_name;
                             m_name = 0;
                        }
                      m_name = new char[strlen(n)+1];
                      strcpy(m_name,n);
                 }
                void displayData()
                {
        			if( m_name )
                      cout<<"Name:"<<m_name<<endl;
                } 
        };
        int main()
        {
              A a1;
              a1.setData( "HELLO" );
              a1.displayData();
        
              A a2;
              a2.setData( "WORLD" );
              a2.displayData();
        
              a2 = a1;
              cout<<"After =:"<<endl;
              a1.displayData();
              a2.displayData();
              
              a1.setData( "FANTASTIC" );
        
              a1.displayData();
              a2.displayData();    
              return 0;
        }
        Run the code, see the output.
        Uncomment the assignment operator and then again run the code, see the output. This is the power of C++.
        Thanks my funda is now cleared.
        Since u create a new memory for the object, as u change value for one object member the other member value wont get affected.

        Raghuram

        Comment

        • vermarajeev
          New Member
          • Aug 2006
          • 180

          #5
          Originally posted by gpraghuram
          Since u create a new memory for the object, as u change value for one object member the other member value wont get affected.

          Raghuram
          What was that? Can you please be more clear?

          Comment

          • gpraghuram
            Recognized Expert Top Contributor
            • Mar 2007
            • 1275

            #6
            Originally posted by vermarajeev
            What was that? Can you please be more clear?
            Hi,
            I am speaking abt the member char* m_name;
            Since in the assignment operator u allocate new memory for this u avoid the shallow copy problem.

            Raghuram

            Comment

            • weaknessforcats
              Recognized Expert Expert
              • Mar 2007
              • 9214

              #7
              Copy constructors versus assignment operators are not involved with deep copy versus shallow copy.

              First, the copy consstructor is to initialize a new object with the data from an existing object. Whether it allocates new memory for m_name is irrelevant.

              Second, the assignment operator replaces the contents of the this object with the contents of the argument object. Whether the assignment operator deletes the current memory, allocates new memory and does a copy for m_name is irrelevant.

              You need to define the relationship between the two objects.

              If the relationshipo is a HAS-A, then you make copies as in the example code in this thread.

              If the relationship is ASSOCIATES-A, then you copy the pointer.

              An association allows one object to change independently from the the other. Case in point: An ordering system. There are 120,000 orders in the system and one of them belongs to vermarajeev. He moves to a new apartment. Takes the cat.

              Now in order to process the change of address, if you have a HAS-A relationship, you have to look at all 120,000 orders to find the ones belonging to vermarajeev. If you have an ASSOCIATES-A, you just change the one object with vermarajeev's addresss. You see, each order just has a pointer to the object with the person's address.

              Objects with pointers are bad news. If you delete one, and you delete the name, you have screwed up all the other objects that might have that address. If you avoid this, you have a massive updating cost.

              So, do not use classes with pointers. Instead of the pointer use a handle object. See the article in the C/C++ Articles form about Handle Classes.

              Above all, do not assume a relationship between objects that have pointers. A deep copy may be exactly what is required OR exactly what is not required.


              He

              Comment

              • vermarajeev
                New Member
                • Aug 2006
                • 180

                #8
                Awesome.:))
                Thanks

                Comment

                Working...