regarding copy constructor

Oct 15, 2014 at 6:26pm
why there is need of copy constructor..actually what was the problem before that raise to the solution like "copy constructors".

dont mind please explain me with some examples too ..

with regards,
vishnu k.
Oct 15, 2014 at 6:32pm
why there is need of copy constructor
Because often, compiler generated one is not sufficient.

what was the problem before that raise to the solution like "copy constructors".
To create a copy of the object?

with some examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct foo
{
    foo(int i)
    {
        arr = new int[i];
    }
    int* arr;
};

int main()
{
    foo x(10); //Create foo object containing array of 10 ints
    x.arr[5] = 42; //Modify said array
    foo y = x; //Creating a copy of x. Using compiler generated CC which does only shallow copy
    y.arr[5] = 9000; //Modifying y array
    std::cout << x.arr[5]; //Woops. Totally unexpected. Why does it outputs 9000?
}
Last edited on Oct 15, 2014 at 6:35pm
Oct 15, 2014 at 6:46pm
HI MiiNipaa,


can we overload the = operator to do the same functionality of copying objects instead of copy constructors.? if no,
why cant we do it?


thanx in advance.
Last edited on Oct 15, 2014 at 6:47pm
Oct 15, 2014 at 7:17pm
We need to have both copy constructor and assigment operator.
When object is initialized, only constructor can be called:
foo y = x; //calls copy constructor, not assigment operator  
This is because only constructors can initialize object.

Assigment operators work on already initialized objects.
Topic archived. No new replies allowed.