Welcome~~~


Another blog:
http://fun-st.blogspot.com/

It is easier to write an incorrect program than understand a correct one.

Monday, February 14, 2011

C++ Notes: Copy Constructors

The important part of copy constructor is that to have a copy constructor override, it can prevent the only "shallow copy" , where in shallow copy, if there is point, two fileds in two differnt object (when using copy construct, such as =) they will point to the same place.
This will cause problem, since it's not a true copy of the original item.


C++ Notes: Copy Constructors
A copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment).
  • A variable is declared which is initialized from another object, eg,
    Person q("Mickey"); // constructor is used to build q.
    Person r(p);        // copy constructor is used to build r.
    Person p = q;       // copy constructor is used to initialize in declaration.
    p = q;              // Assignment operator, no constructor or copy constructor.
  • A value parameter is initialized from its corresponding argument.
    f(p);               // copy constructor initializes formal value parameter.
  • An object is returned by a function.
C++ calls a copy constructor to make a copy of an object in each of the above cases. If there is no copy constructor defined for the class, C++ uses the default copy constructor which copies each field, ie, makes a shallow copy.

No comments:

Post a Comment