Thread: Copy constructor

  1. #1
    Unregistered
    Guest

    Copy constructor

    Any one can tell me what is the responsiblity of the copy constructor ?

    -thanks

  2. #2
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    Posts
    4,829
    There are several places in C++ programming where a copy of an object is made. If, for example, you pass an object to a function, the normal "pass by value" mechanism is used, and a copy of the object is made.

    If you have not specified a copy constructor, the compiler uses the default copy constructor to make the object. The default is a bitwise copy, i.e. it is exactly the same as the object in the calling routine. When the called function exits, the copy goes out of scope and is destroyed.

    In many cases, this is not a problem, but supposing the object contains a pointer to some dynamically allocated memory? The bitwise copy will contain exactly the same address, and if, as it should, the destructor for the object frees that memory, the bitwise copy will free memory that the original object in the calling routine still "thinks" is allocated - a disaster waiting to happen.

    With a copy constructor, you can create a new dynamic memory element, and copy the contents of the original objects dynamic structures to the new object. When it goes out of scope and is destroyed, it is the copies that are deallocated and the original object is not damaged.

    There are other reasons, but in general it is wise to build a copy constructor for all but the simplest of classes.
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

  3. #3
    Unregistered
    Guest

    copy constructor

    Thank you <adrianxw> for your explaination. It was very detailed and useful

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Copy constructor
    By dude543 in forum C++ Programming
    Replies: 26
    Last Post: 01-26-2006, 05:35 PM
  2. illegal copy constructor required?
    By ichijoji in forum C++ Programming
    Replies: 1
    Last Post: 03-08-2005, 06:27 PM
  3. Linked list copy constructor issue
    By Craptastic! in forum C++ Programming
    Replies: 1
    Last Post: 08-03-2003, 08:30 PM
  4. copy constructor
    By Eber Kain in forum C++ Programming
    Replies: 1
    Last Post: 09-30-2002, 05:03 PM
  5. Using strings with the copy constructor
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 08-29-2001, 03:04 PM