WHAT DOES A COPY CONSTRUCTOR DO?

Mar 18, 2012 at 8:51am
Hi there, can somebody tell me what a copy constructor does? and when do u know you need one? thanking you in advance.
Mar 18, 2012 at 9:58am
a copy constructor looks like this:
1
2
3
4
5
6
class foo
{
       public:
       int x;
       foo (foo a) {x=a.x;}
       }

So basicly, it costructs a new object out of an existing one, copying all of it's elements into itself.
Mar 18, 2012 at 10:05am
thank you very much viliml.
Mar 18, 2012 at 10:48am
Note that while viliml's example is not incorrect, it is not a good idea to use pass by value for copy constuctors. The canonical form uses pass by const ref.

And constructors should use the constructor initializer list to initialize member variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Point
{
private:
    int m_x;
    int m_y;
    // etc (e.g. color)

public:
    Point()
    : m_x(0), m_y(0) // etc 
    {
    }

    Point(int x, int y)
    : m_x(x), m_y(y) // etc 
    {
    }

    Point(const Point& that)
    : m_x(that.m_x), m_y(that.m_y) // etc 
    {
    }

    // etc
};

Last edited on Mar 18, 2012 at 11:12am
Topic archived. No new replies allowed.