As per below code snippet it is clear that in below class a if we don't introduce assignment operator
despite of having pointer values it works fine as memory allocation is done explicitly by declaring s2 object on heap .
can anybody suggest, if same canbe achieved without declaring copy constructor explicitly despite of having pointer fields .
A (string );
A s1("s1") ;
A * s2 = new A ("s2");
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.
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:
Derived1* s2 = new Derived1("s2");
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!
Thanks for your explanation but still i really confused about memory leak thing as i never ever
faced memory leak issue even while trying with compiler generated assignment operator versions.
Could you help me out to reproduce the same.
Note:I am using Dev-c++18.104.22.168 compiler .