COPY CONSTRUCTOR

What is a copy constructor and when is it called?
closed account (SECMoG1T)
AFAIK, a copy constructor is used to create copies of the class type objects, for example when we pass a class type obj as a parameter to a functions by value or when we initialize newly created objects from existing objects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Foo
{
   Foo(const Foo& F_obj)
    ///members
}

void do_something(Foo obj);

int main()
{

  Foo obj;
  Foo obj1=obj;//copy constr called

  do_something(obj);///cpy cnstr called 




Note: copy constructors usually takes their params by const reference or *at-least* normal lvalue reference coz if they took non_ref parameters they would be required to construct their own arguments which would lead to an infinite recursion though standard compilers will not allow you to define such constrs.



Last edited on
If you don't supply a copy constructor, the compiler will generate one if needed. However, the compiler generated copy constructor only does a shallow copy of members.

If you need the copy constructor to do more than a shallow copy, then you need to provide your own constructor.

Consider if class Foo contains pointer to an object allocated with new Bar. After a shallow copy, you have two instances of Foo each with a pointer to the same instance of Bar. If both instances of Foo now try to delete Bar, you're going to have a problem because only one instance exists.
thanks guys....
Copy constructor is used to copy class objects data into other
Consider
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MyClass {
...
};

void func(MyClass c)
{
...
}

int main()
{
    MyClass c1;
    func(c1);
}

By default, C++ passes parameters by value, so when you call func(), the compiler makes a copy of MyClass instance. It does that via the Copy Constructor.

There are other places where copy constructors are used, but this is a good example.
> By default, C++ passes parameters by value
no, they are passed by whatever way you have specified in the prototype of the function.


@OP: the questions at the end of the chapter are for self-evaluation. Consider reviewing the material if you can't answer them.
no, they are passed by whatever way you have specified in the prototype of the function.

Yes that's a much clearer way to put it. I was thinking along the lines of "if you just give the type of the parameter" but that is quite different from "default." Thanks.
Topic archived. No new replies allowed.