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

C++ Tutorial - Copy Constructors

By , About.com Guide

8 of 10

An Example of Copy Constructors and Assignment Operators

Download Example 1
This is a longish example with a base class phonerec and a derived class phonebillrec. All methods have a cout so you can see when they are called and the order of calling.

This example is too long to list here but the main part is

int main(int argc, char* argv[])
{
    phonebillrec p; // calls a default parameter "Me"
    cout << "----" << endl;
    phonebillrec p2(23.45) ;
    cout << "----" << endl;
    p2.name="Fred";

    phonebillrec p3(p2) ;
    cout << "----" << endl;
    phonebillrec p4;
    cout << "----" << endl;
    p4=p2;
    cout << "----" << endl;
    cout << "Name = " << p3.name << endl;
    return 0;
}
The output is
Default Constructor phonerec
Default Constructor phonebillrec
----
Default Constructor phonerec
Default Constructor phonebillrec
----
Copy Constructor phonerec
Copy Constructor phonebillrec
----
Default Constructor phonerec
Default Constructor phonebillrec
----
Assignment Operator phonerec
Assignment Operator phonebillrec
----
Name = Fred

On the next page : More about Example 1

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

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

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

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. An Example of Copy Constructors and Assignment Operators

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

All rights reserved.