473,938 Members | 6,227 Online
Bytes | Software Development & Data Engineering Community
+ 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 2577
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
1822
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 assignment, should copy constructor and assignment operator be unnecessary? 2. If a base class have a pointer member, should its derived classes also need copy constructor and assignment operator, no matter if a derived class itself has a...
8
2993
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 or the default constructor is automatically called instead" Why cant the compiler do this on its own. if we are making an object through copr construction for an inherited class , then why not simply call the corresponding copy constructors for...
10
2593
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, we do not need to use the copy-constructor. So depending on the above reasoning I can avoid call by value and return by value for class objects, this bypasses the problem or it seems to me like that. Could any one give me some simple examples...
8
449
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 copies of classes with members with static or dynamic memory allocation. However to do this it requires the programmer to override the default copy constructor, the destructor & operator=. I wrote a small program to test if i can doa deep copy...
13
5039
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 to make it more manageable. Below is a draft of a document that I plan to give to my introductory C++ class. Please note that I have purposely left out any mention of safety issues in the ctors which could be resolved thru some combination...
1
2135
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 reference member, the compiler will not be able to synthesize an assignment operator for your class. It actually helps to think of a reference member as a const member (since it cannot be made to reference any other object once it has been initialized). ...
2
6265
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 manipulation. Now A has a copy constructor and assignment operator. What will happen if copying goes on in B? Do I need to have an overloaded set of functions which call the same copy functions that A has available? Or are they virtual in the...
22
3649
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 v);
13
3993
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 is much appreciated. JD
9
2911
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 Foo() is included, i believe. };
0
10125
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11509
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
11095
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11281
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
8207
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6072
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6283
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4900
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3495
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.