This doesn't work like you think it does. You never initialise the pointer m_p to anything. Also, on line 17 you leak the memory that you new on line 16. And I think that line 18 will the cause a stack corruption or segfault or something.
Here's what your code does:
- Line 15: Creates a new
A on the stack. s1.m_p doesn't point at anything in particular - Line 16: Creates a new
A on the heap. s2.m_p doesn't point at anything in particular - Line 17: Aim
s2 at the adress of s1. This leaks the memory that you assigned in the previous line, since there is now nothing in your program that points to that space in the heap. - Line 18: Calling
delete on a pointer calls the destructor of the thing that the pointer points to (s1 in this case). It then tries to make that memory available again. However, the memory in question is on the stack. I don't know what happens in this case, but it can't be good!
The default copying of a struct is always an element-by-element value copy. This means that if you have pointer members, the values of those pointers are copied, not the data that the pointers point to. If you want to do this, then you have to make your own copy constructor. Allocating a struct using new doesn't change this.
ravenous
Practically a Master Poster
681 posts since Jul 2005
Reputation Points: 286
Solved Threads: 111
Skill Endorsements: 9
Line 60 does not achieve a copy of s1. The calls to show() display the same thing for s1 and s2, but that's because they're accessing the same object, not two objects that have the same values. Try this addition to your main:
int main()
{
Derived1 s1("s1");
s1.setVal(20);
s1.show();
Derived1* s2 = new Derived1("s2");
s2->setVal(100);
s2->show();
s2=&s1; // this is aiming s2 at the memory for s1 (and leaking the old memory for s2 that you newed)
s1.show(); // Shows s1
s2->show(); // Also shows s1!
// Now try to change s2
s2->SetValue( 5 );
s1.show(); // Now s1 has the same value that you just put into s2!
getch();
}
ravenous
Practically a Master Poster
681 posts since Jul 2005
Reputation Points: 286
Solved Threads: 111
Skill Endorsements: 9
can any body suggest if same way can we perform the copy constructor as well.
Written here, in your other thread:
Click Here
Lucaci Andrew
Practically a Master Poster
649 posts since Jan 2012
Reputation Points: 91
Solved Threads: 91
Skill Endorsements: 12