3.12 The Copy Constructor

The copy constructor is a special constructor that is automatically a part of every class. It allows a copy to be made of an object. The default copy constructor creates an identical copy of the object, so states have the exact same values. The default copy constructor can be called simply by:

  int main()
    Account a = Account("Derek Molloy",35.00,34234324); 
    Account b(a);
    b.display();   // exact same output, both have a balance of 35.00 Euro


    a.display();   // a now has a balance of 135.00
    b.display();   // b has the same balance of 35.00

The full source code for this example is in DefaultCopyConstructor.cpp. This call creates a new Account object, with its own memory space, with the exact same state values as the original Account object.

This facility provides limited functionality. For example, if the details of one Account object were being used to create another Account object, creating another account for the same owner, we can modify the copy constructor to provide specific copy behaviour.

  class Account{


    int accountNumber;
    float balance;
    string owner;


    Account(string owner, float aBalance, int anAccountNumber);
    Account(float aBalance, int anAccountNumber);
    Account(int anAccountNumber);
    Account(const Account &sourceAccount);



  Account::Account(const Account &sourceAccount):
	accountNumber(sourceAccount.accountNumber + 1), 
	owner (sourceAccount.owner) {}

The full source code for this example is in ModifiedCopyConstructor.cpp.

The output from this example can be seen in Figure 3.10, “The Output from the Modified Copy Constructor Example.” (The same main() method is used). In this case the copy constructor has been modified to copy the account holder name, but to zero the balance of the new account and to set the new account number to be the last one plus 1 (this is not an ideal implementation, just an example).

Figure 3.10. The Output from the Modified Copy Constructor Example.

The Output from the Modified Copy Constructor Example.

These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way.
Derek Molloy,
19 Oct 2013, 05:12
Derek Molloy,
26 Oct 2013, 03:22