Technical Interview Questions

The largest pool of technical questions with answers, explantions, code and detailed analysis

Constructors: Copy Constructors, What, Why, How, When … (C++)

Posted by tekpool on December 22, 2006

As the name suggests, a copy constructor is called whenever an object is copied. This happens in the following cases:

  • When an object is create from another object during initialization (Class a = b)
  • When an object is created from another object as a parameter to a constructor (Class a(b))
  • When an object is passed by value as an argument to a function (function(Class a))
  • When an object is return from a function (Class a; … return a;)
  • When an exception is thrown using this object type (Class a; …. throw a;)

Whenever an object copying scenario like the ones above is encountered, the copy constructor is invoked. A copy constructor can be either user defined or compiler defined. If the user does not define a copy constructor, then the default compiler defined copy constructor will be invoked during object copy scenarios. The default copy constructor is a bit-by-bit (member wise) copy. But often you will encounter situations where this is not desirable since this is just a shallow copy and sometimes you do not want an exact copy or you may want to do some custom resource management. 

 
Class t1; 
Class t2=t1; // Copy Constructor is invoked 
Class t3; 
t3=t1; // Assignment Operator is invoked 

In the Code snippet above, the constructor is invoked twice, during the creation of objects t1 and t3. (Creation of t2 invokes the copy constructor). The destructor is invoked 3 times though. In cases like these, if the constructor allocates memory and the destructor frees it, you will see the t2’s destructor will try to delete already deleted memory, if t1 is destroyed before t2 or vice-versa. Meaning, you are hosed. To prevent this, a user defined copy constructor needs to be provided. which doesn’t do a simple bit-by-bit but rather assigns memory specifically for the object and does a deep copy if required.

To define a copy constructor for a class T, a constructor of the following format needs to be defined.

 
Class T 
{ 
… 
    T(const T& t) 
… 
} 

You need a reference because if it were T(T t), it would end in a infinite recursion. (Was that an oxymoron?). const because you are not changing the object in the constructor, you are just copying its contents

Some Rules of Thumb:

  • Don’t write a copy constructor if a bit-by-bit copy works for the class
  • If you defined your own copy constructor, it probably because you needed a deep copy or some special resource management, in which case, you will need to release these resources at the end, which means you probably need to define a destructor and  you may also want to think of overloading the assignment operator (beware of self-assignment)
About these ads

24 Responses to “Constructors: Copy Constructors, What, Why, How, When … (C++)”

  1. jacky said

    thanks for the helpful programs. These were greatly helpful for preparing for the latest and recent microsoft placement papers 2008 and its technical interviews questions were answered easily by me thanks to your helpful information. They asked me in hr interview also and i was good at that. various languages questions were answered good..

  2. jacky said

    thanks for the helpful programs. These were greatly helpful for preparing for the latest and recent microsoft placement papers 2008 and its technical interviews questions were answered easily by me thanks to your helpful information. They asked me in hr interview also and i was good at that. various languages placement questions were answered good..

  3. master zhao said

    “The default copy constructor is a bit-by-bit”.
    This is a common misconception shared by many inexperienced programmers. The default copy ctor is not bit-by-bit. For each member, it invokes the copy constructor for that member, for premitive type (including pointer) the above is true. In general one should never try to write a copy constructor, trust me they are not trivial. Never use raw pointer, use a shared_ptr instead.

  4. Swagato said

    Thank you for the information. It made me able to understand more easy. But can you tell me the importance of Copy Constructor?

  5. Abhash Kumar Singh said

    Please tell me while defining cpoy constructor why do we use pass by reference not pass by value?

  6. priyanka jaiswal said

    Thank you.The content about the copy constructor really helped me a lot to understand the topic.

  7. thisIsCraaaaP said

    IMO, this is a piece of sh!t page, it’s about 1/5th the size of normal tutorials and covers even less, so….. virtually nothing.
    There are so many things to talk about when talking about copy ctor’s it’s just a shame I have to click on 1001 different websites to read all the different articles. Not one of them yet have shown use of deep copy array or MD copying. Sick of all the fuken girls on the interwebs who think they are good enough to train others.

  8. Mohd.Owais said

    Thax for giving valuable information.Its helps me a lot.

  9. pradeep said

    thanks a lot yaaa…..i got knew things in which u hav explained in a situation when copy constructor is called

  10. Thanks..The Explanation is simple and useful..

  11. Sudhir Dhekane said

    thanx… now i realize exact CC

  12. Shanwaz said

    Very useful programs…thanks..dude..
    Technical interview questions

  13. Yellaiah said

    It’s so good explanation about Copy Constructors..

  14. marshal said

    thank you gaga

  15. NHL said

    NHL…

    [...]Constructors: Copy Constructors, What, Why, How, When … (C++) « Technical Interview Questions[...]…

  16. Richa said

    Priyanka, give me your creamy @$$

  17. Harinath said

    Thank you very much..for Copy Constructors, What, Why, How, When …really this is very nice..

  18. Sow said

    Thank you very much. It’s nice.

  19. These are truly impressive ideas in on the topic of blogging.
    You have touched some fastidious points here. Any way keep up
    wrinting.

  20. avakash5 said

    hmm its really gud info… thanx!!

  21. avakash5 said

    but i am getting confuse while default copy constructors does bit-by-bit copy or what??

  22. keerthi said

    Thank u for ur information….one request give some more small snippets….

  23. panqnik said

    Thank your for this post. I’ve written similar article on my blog, here: http://blog.szulak.org/dev/copy-constructor-and-copy-assignment/
    Every feedback is very welcome :)

  24. Canhelp said

    When is copy constructor called?

    http://www.writeulearn.com/copy-constructor-called-itself/#comment-13

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 28 other followers

%d bloggers like this: