1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - Copy Constructors

By David Bolton, About.com

9 of 10

How Example One Works

A Difference between Assignment Operator and Copy Constructor

p4 is assigned the value of p2 and this calls the assignment operator. where as p3 is initialized by a copy constructor from p2, but both should have the same value.

Apart from the fact that the copy constructor creates an instance of phonebillrec, there is another difference. If the class is derived from a base class (as phonebillrec is derived from phonerec) then the base class constructor must be called before the derived class. It's just like constructing a multi storey building. You need a ground floor with stairs before you can climb up to the 1st floor.

A copy constructor in a derived class needs a copy constructor in the base class, or it will call the base class default constructor. You must explicitly code the base class copy constructor and call it in the initializer list of the derived class.

Here is the copy constructor for phonebillrec

// Copy Constructor
phonebillrec(phonebillrec & rec) : phonerec(rec) {
  cout << "Copy Constructor phonebillrec" << endl;
  bill = rec.bill;
}
Notice the : phonerec(rec) - this is the initializer list part that initializes the base object. If you comment this out in example 1, like this
/* : phonerec(rec) */
then the default constructor for phonerec is called instead and the phonerec part of phonebillrec is not copied.

Assignment operators do not have defaults, so you must call the base class assignment operator in the derived class assignment operator so that the base class members are assigned values. This line calls the base class assignment operator using the :: notation.

phonerec::operator=(rhs); // Call base class assignment operator

On the next page : Summing Up

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. How Example One Works

©2009 About.com, a part of The New York Times Company.

All rights reserved.