copy constructor

This is a discussion on copy constructor within the C++ Programming forums, part of the General Programming Boards category; I am having trouble understanding 2 things. 1. the difference between a copy constructor and an operator= What the actual ...

  1. #1
    Unregistered
    Guest

    copy constructor

    I am having trouble understanding 2 things.

    1. the difference between a copy constructor and an operator=
    What the actual use of the copy constructor is. I think I get the
    operator=

    2. do we actually call the operator= or is it called whenever it is
    required?

  2. #2
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    The copy constructor, like all constructors, is only called once in an object's lifetime. Even when you do something like this,

    type a = b; // looks like assignment, but isn't

    It's the same as

    type a(b); // it's actually a copy constructor call

    However, if you want to change the state of an object to another object AFTER it has been created, that is when you use the operator =.

    Code:
    type a(2);  // type(int) constructor
    type c(a);  // type(const type&) [copy constructor]
    type b;     // type() [default constructor]
    b = a;       // operator = (type, type)
    All calls to the = operator are explicit, but not everything that looks like it's using the = operator actually does.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  3. #3
    Registered User
    Join Date
    Mar 2002
    Posts
    203
    the copy constructor is also called when an object is passed-by-value to a function and when a function returns an object

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, 09:30 PM
  4. copy constructor
    By Eber Kain in forum C++ Programming
    Replies: 1
    Last Post: 09-30-2002, 06:03 PM
  5. Using strings with the copy constructor
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 08-29-2001, 04:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21