0
I am not getting the concept of copy constructor in c++
how can dangling pointer affect the object?
1 Antwort
+ 3
A copy constructor is used to initialize an object using an existing object of the same type.
For example :
class B{} ;
class A{
int x, y;
B* pb;
public:
A() {x=y=0; pb=new B;}
A(const A& a){x=a.x; y=a.y; pb=a. pb;}
~A() {delete pb;}
} ;
A* a1 = new A();
A* a2 = new A(a1) ;
You can see that a2 is constructed using a1's members in it's copy constructor.
But there is a fatal flaw! Both objects' pb member now points to the same instance of class B.
As soon as you, for example, do the following:
delete a1;
delete a2;
The deletion of a1 will delete pb in its destructor, but now you will have a dangling pointer pb in a2, and the call to delete a2 will now throw a null pointer exception as soon as it tries to delete pb again.