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

C++ Tutorial - Copy Constructors

By , About.com Guide

5 of 10

Creating and Using Copy Constructors

Copy Constructors - Another Way to Create an Objects

To create an object from an existing object requires a special type of constructor, called a copy constructor. It allocates memory but copies the POD (Plain Old Data) values from another object of the same class. It has one parameter, a reference to an existing object. The last page of this lesson looks in detail at POD.

Like a default constructor, one is supplied by the compiler if there is a need for one and you haven't supplied it. If the object being copied is POD then no problems, i.e. no references, virtual functions or other complexities which affects how the data is stored in the object.

E.g. a pointer to non-const data owned by the object will be cloned and when the original object is destroyed it will release ownership of the pointer. So will destroying the new object. Freeing an object twice is a bad thing that can lead to unexpected crashes. So if you have non POD in your object then you must write a copy constructor and take care of the copying. For POD you can let the compiler do the hard work!

#include <iostream>

using namespace std;

struct SomeData {
    int rd;
    SomeData(SomeData & ref) {
    cout << "Copy Constructor called" << endl;
    rd = ref.rd;
    }

    SomeData() : rd(0) {};
};

int main() {
    SomeData s;
    s.rd =9;
    SomeData s2=s;
    cout << s2.rd << endl;
    return 0;
}
This example of a class containing POD shows a copy constructor being used. Comment out the copy constructor and it will still output the same result.

On the next page : An example of a copy constructor

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. Creating and Using Copy Constructors

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

All rights reserved.