Thread: Copy Constructor

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    219

    Copy Constructor

    I wanna learn Copy Constructor.
    So if I rely upon teh Compiler to make one I cant learn.
    Please tell me wheather My Copy Constructor is Correct or not ??
    Code:
    Point(const Point&);
    Code:
    Point::Point(const Point& pt){
    	*this = pt;
    }

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    In a sense, it's correct. In another, it's not.

    It works in this concrete case, but:

    1) It doesn't work if the class contains non-assignable data, such as const members or references.
    2) It doesn't work if the copy assignment operator requires a properly initialized object.
    3) You can't implement copy assignment in a similar way.
    4) It doesn't work if any member doesn't have a default constructor.
    5) Even if they have, the results may be undesirable or simply inefficient.

    As I told you in the other thread, implement an extensible array. It's simple, and it shows you what a copy constructor is actually for. You don't really learn anything from implementing trivial copy constructors.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    Registered User
    Join Date
    Jun 2007
    Posts
    219
    So would I do like this ??
    Code:
    Point::Point(const Point& pt) : x(0), y(0){}
    ??

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    No, that just assigns 0 to both components. You want the values of the argument. I showed you the correct implementation in another thread.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

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