Sponsored Links

Results 1 to 2 of 2

Thread: explain the copy constructor, shallow copy, and deep copy with examples and c++ code

  1. #1
    Senior Member saneha's Avatar
    Join Date
    Apr 2011

    18 explain the copy constructor, shallow copy, and deep copy with examples and c++ code

    Sponsored Links1

  2. #2
    Administrator Vuhelper's Avatar
    Join Date
    Apr 2011
    A copy constructor is used to initialize a newly declared Object from an existing Object. This makes a deep copy like assignment.
    A shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied -- the field in both the original object and the copy will then point to the same dynamically allocated memory.

    A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disastrous consequences.

    I am giving you one example which perform deep copy in this example if you do not override copy constructor then it will give run time error, not perform as what we want so it will be help full for understanding why we have tooverride copy constructor if compiler provide it by default.

    class base
    int *a;
    void allocate()
    a = new int(10);
    void disp()
    base(base &b)
    a = new int(*(b.a));
    delete a;

    int _tmain(int argc, _TCHAR* argv[])
    base *b1 = new base;
    base *b2 = new base(*b1);
    delete b1;
    delete b2;
    return 0;

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Replies: 0
    Last Post: 02-05-2013, 02:08 AM
  2. What is the syntax of copy constructor in c 2011
    By saneha in forum C++ Programing
    Replies: 1
    Last Post: 05-02-2011, 05:36 PM
  3. Replies: 1
    Last Post: 04-29-2011, 08:19 AM
  4. Replies: 1
    Last Post: 04-24-2011, 06:40 PM
  5. Replies: 4
    Last Post: 07-28-2010, 01:29 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
-: Vuhelp Disclaimer :-
None of the files shown here are hosted or transmitted by this server. The links are provided solely by this site's users. The administrator's or staff of Vuhelp.net cannot be held responsible for what its users post, or any other actions of its users. You may not use this site to distribute or download any material when you do not have the legal rights to do so. It is your own responsibility to adhere to these terms. If you have any doubts about legality of content or you have any suspicions, feel free to contact us.
Online Education | JhelumSoft | Jobs