473,473 Members | 1,768 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

copy constructor V/s assignment operator

180 New Member
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

Expand|Select|Wrap|Line Numbers
  1. class MyObject 
  2. {
  3. public:
  4.   MyObject();      // Default constructor
  5.   MyObject(MyObject const & a);  // Copy constructor ( copying happens by deep copy)
  6.   MyObject & operator = (MyObject const & a) // Assignment operator (copying happens by shallow copy)
  7. }  
Can someone please make me understand how actually the copying happens in both copy constructor and an assignment operator

Thanks
Aug 16 '07 #1
7 2555
gpraghuram
1,275 Recognized Expert Top Contributor
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

Expand|Select|Wrap|Line Numbers
  1. class MyObject 
  2. {
  3. public:
  4.   MyObject();      // Default constructor
  5.   MyObject(MyObject const & a);  // Copy constructor ( copying happens by deep copy)
  6.   MyObject & operator = (MyObject const & a) // Assignment operator (copying happens by shallow copy)
  7. }  
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
Aug 16 '07 #2
vermarajeev
180 New Member
I think this is more clearer,
Expand|Select|Wrap|Line Numbers
  1. class A
  2. {
  3.    char* m_name;
  4.    public:
  5.          A(){ m_name = 0; }
  6.          A(const char* n)
  7.          {
  8.               m_name = new char[strlen(n)+1];
  9.               strcpy(m_name,n);
  10.          }
  11.          /*A& operator = (const A& obj)
  12.          {
  13.             if( this != &obj )
  14.             {
  15.                 setData(obj.m_name);
  16.             }
  17.             return *this;
  18.          }*/
  19.          void setData(const char* n)
  20.          {
  21.              if( m_name ) 
  22.                 { 
  23.                      delete m_name;
  24.                      m_name = 0;
  25.                 }
  26.               m_name = new char[strlen(n)+1];
  27.               strcpy(m_name,n);
  28.          }
  29.         void displayData()
  30.         {
  31.             if( m_name )
  32.               cout<<"Name:"<<m_name<<endl;
  33.         } 
  34. };
  35. int main()
  36. {
  37.       A a1;
  38.       a1.setData( "HELLO" );
  39.       a1.displayData();
  40.  
  41.       A a2;
  42.       a2.setData( "WORLD" );
  43.       a2.displayData();
  44.  
  45.       a2 = a1;
  46.       cout<<"After =:"<<endl;
  47.       a1.displayData();
  48.       a2.displayData();
  49.  
  50.       a1.setData( "FANTASTIC" );
  51.  
  52.       a1.displayData();
  53.       a2.displayData();    
  54.       return 0;
  55. }
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.
Aug 16 '07 #3
gpraghuram
1,275 Recognized Expert Top Contributor
I think this is more clearer,
Expand|Select|Wrap|Line Numbers
  1. class A
  2. {
  3.    char* m_name;
  4.    public:
  5.          A(){ m_name = 0; }
  6.          A(const char* n)
  7.          {
  8.               m_name = new char[strlen(n)+1];
  9.               strcpy(m_name,n);
  10.          }
  11.          /*A& operator = (const A& obj)
  12.          {
  13.             if( this != &obj )
  14.             {
  15.                 setData(obj.m_name);
  16.             }
  17.             return *this;
  18.          }*/
  19.          void setData(const char* n)
  20.          {
  21.              if( m_name ) 
  22.                 { 
  23.                      delete m_name;
  24.                      m_name = 0;
  25.                 }
  26.               m_name = new char[strlen(n)+1];
  27.               strcpy(m_name,n);
  28.          }
  29.         void displayData()
  30.         {
  31.             if( m_name )
  32.               cout<<"Name:"<<m_name<<endl;
  33.         } 
  34. };
  35. int main()
  36. {
  37.       A a1;
  38.       a1.setData( "HELLO" );
  39.       a1.displayData();
  40.  
  41.       A a2;
  42.       a2.setData( "WORLD" );
  43.       a2.displayData();
  44.  
  45.       a2 = a1;
  46.       cout<<"After =:"<<endl;
  47.       a1.displayData();
  48.       a2.displayData();
  49.  
  50.       a1.setData( "FANTASTIC" );
  51.  
  52.       a1.displayData();
  53.       a2.displayData();    
  54.       return 0;
  55. }
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
Aug 16 '07 #4
vermarajeev
180 New Member
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?
Aug 16 '07 #5
gpraghuram
1,275 Recognized Expert Top Contributor
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
Aug 16 '07 #6
weaknessforcats
9,208 Recognized Expert Moderator Expert
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
Aug 16 '07 #7
vermarajeev
180 New Member
Awesome.:))
Thanks
Aug 17 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: away | last post by:
1. When a class defined with a member of pointer type, it's necessary to have a copy constructor and assignment operator. If don't pass objects of such class as value in a function and don't do...
8
by: trying_to_learn | last post by:
Why do we need to explicitly call the copy constructor and the operator = , for base class and member objects in composition? ....book says "You must explicitly call the GameBoard copy-constructor...
10
by: utab | last post by:
Dear all, So passing and returning a class object is the time when to include the definition of the copy constructor into the class definition. But if we don't call by value or return by value, ...
8
by: rKrishna | last post by:
I was trying to understand the real need for copy constructors. From literature, the main reason for redfinition of copy constructor in a program is to allow deep copying; meaning ability to make...
13
by: blangela | last post by:
I have decided (see earlier post) to paste my Word doc here so that it will be simpler for people to provide feedback (by directly inserting their comments in the post). I will post it in 3 parts...
1
by: blangela | last post by:
3.0 Advanced Topic Addendum There are a few cases where the C++ compiler cannot provide an overloaded assignment operator for your class. If your class contains a const member or/and a...
2
by: Henrik Goldman | last post by:
Hi, Lets say you have class A which holds all data types as private members. Class B then inherits from A and does *only* include a set of public functions which uses A's existing functions for...
22
by: clicwar | last post by:
A simple program with operator overloading and copy constructor: #include <iostream> #include <string> using namespace std; class Vector { private: float x,y; public: Vector(float u, float...
13
by: JD | last post by:
Hi, My associate has written a copy constructor for a class. Now I need to add an operator = to the class. Is there a way to do it without change her code (copy constructor) at all? Your help...
9
by: puzzlecracker | last post by:
From my understanding, if you declare any sort of constructors, (excluding copy ctor), the default will not be included by default. Is this correct? class Foo{ public: Foo(int); // no...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.