tags:

views:

107

answers:

3

Possible Duplicate:
question about copy constructor

if I have this snippet of the code

A a1(i);
A a2 = a1;
A *pa1 = new A(a2);

can somebody please explain what exactly the last line does, it makes copy of the a2 and pointer for this new object is pa1 or it just creates pointer for a2, thanks in advance

+3  A: 

The last line creates a new object A, to which pa1 points, and its contents are the same as those of a2.

I believe this example demonstrates the use of a constructor with arguments (first line), a copy constructor (second line) and another copy constructor (last line). In the end all the three object will have the same contents.

PeterK
The second line may be a copy constrictor (try it)
Martin York
You are correct. I edited my answer.
PeterK
+2  A: 

On line 1, you are creating an A object, calling the A constructor, passing in 1, and assigning it to a1.

On line 2, you are making a copy of a1.

On line 3, you are creating a new A object, calling the A copy constructor, passing in the copied object a1, and returning a pointer to this object in memory.

Jacob Relkin
line 3: you mean copy constructor.
Alan
Be careful how you use the term "new" in the above paragraph
Martin York
+2  A: 

The first line creates a new instance of the A class (a1) on the stack (so it's lifetime is limited to the current scope). The constructor used will depend on the type of i.

The second line will create another instance of the A class on the stack (a2). The copy-constructor will be used, so if the copy operation is implemented sensibly (or the default one makes sense for your class) it will be a copy of the source instance (a1). If no compatible copy constructor is accessible a compiler error will occur.

The third line returns a pointer to a new instance of the class A (pa1) which is allocated on the heap. It's lifetime must be explicitly managed and the actual object can outlive the scope of the pointer itself. As in the second case, it's copied using the copy constructor.