Copy Constructor

Well this question is similar to what I have earlier asked about destructors. But I just want to confirm about it.

When compiler automatically creates a copy constructor for us? Why should we ever write one?

Is it because it is done for simple primitive data types??? Or some other reason. If someone give an example it would be of great help.

Thanks in advance.
You should write your own copy constructor if you have a dynamically allocated object (like something allocated with new/new[]) because the default copy ctor will simply copy the point and not reallocate the buffer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class C
{
public:
C() { p = new int; }
~C() { delete p; }

protected:
  int* p;
};

void func_ok()
{
  C a;   // calls default ctor (a.p created with new)
}        // calls dtor (a.p deleted)

void func_bad()
{
  C a;     // calls default ctor (a.p created with new)
  C b(a);  // calls copy ctor (b.p not allocated, but instead, b.p = a.p)
}          // calls both dtors, so both a and b try to delete the same pointer (error/crash) 


The same problem happens with the assignement operator.. so that should be overloaded as well in these types of cases. This is solved by writing a copy ctor and assignement operator overload:

1
2
3
4
5
6
7
8
class C
{
public:
 // ...
C(const C& c) { p = new int;  *p = *c.p; }
C& operator = (const C& c) { *p = *c.p;  return *this; }
 // ...
};


There are other uses for a copy ctor, as well. Like if you want to make an object that reference counts rather than completely copying a buffer or something.
Last edited on
To answer the other question, the compiler always gives you a member-wise copy copy constructor unless you explicitly define one yourself.
Topic archived. No new replies allowed.