Re: Copy C'tor - doubt
On Thu, 19 Nov 2009 17:04:48 CST, AY wrote:
[snip]
int main()
{
AB* ab = new AB(7);
//AB* cd = new AB;
AB* cd(ab);
return 0;
}
My Qn is in the statement - AB* cd(ab);
Does object 'cd' uses the same memory as object 'ab' ?
No.
Is any memory allocated in the heap for 'cd' like 'ab' [ I do not
think, maybe I'm wrong ] ?
No. Both 'ab' and 'cd', being automatic variables, are allocated on the
stack. They end up containing the same value, though.
What happens here exactly.
AB* ab = new AB(7);
Here you declare a pointer 'ab';
then you allocate an object of type AB on the heap;
finally, you put the address of the newly-allocated AB object in 'ab'.
Now 'ab' points to an AB.
AB* cd(ab);
Here you declare another pointer, 'cd', and initialize it with 'ab'.
You didn't invoke AB's copy constructor, only a pointer's copy constructor,
so to say. Because 'cd' is not an AB -- it's a 'pointer to an AB'.
Now both 'ab' and 'cd' point to the same AB.
To invoke AB's copy constructor, you might have done this:
AB* ef = new AB(*ab);
This creates a new AB object, with its own memory, on the heap.
The new object is a copy of the object pointed to by 'ab' (if your copy
constructor does its job correctly).
The address of the new object is kept in 'ef'.
I couldn't say 'new AB(ab)' because 'ab' is a 'pointer to an AB', while
your copy constructor expects 'an AB', so I dereferenced 'ab' by saying
'*ab'.
HTH.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]