Pointer data members!

From many literature sources(online and print), one is instructed that if a class has a pointer data member, one needs to explicitly overload the assignment operator, write a copy constructor, and include a destructor. I have consistently observed this rule.

However, just to see what would happen, I designed a class queueType for a queuing system which has a pointer data member to hold the queue elements. I declared two objects, say A and B, of class queueType, and read data into just A. I did not include a copy constructor and I did not overload the assignment operator! I then wrote the statement

B = A;

And yet, the assignment operation went through correctly without any problems!! Object B had all the data I only read into object A.

Why is this so??


What happens is that the default compiler-generated copy constructor gets used, so both classes have the same pointer. When they go to free the pointed-to data, it gets done twice for the same data. If they try to change the pointed-to data, both instances see the changed data. It's a mess.
Last edited on
The compiler-generated copy constructor and assignment operator will copy all the members, including pointers, from the source to the destination. The problem is that once that copy is made, it's not longer possible to know at destruction time which pointers should be deleted and which should not. Once both A and B go out of scope, at least one pointer will be deleted twice, corrupting the heap.
That literature must have been pretty lousy if it just recited that rule like a mantra without explaining why it exists.
Topic archived. No new replies allowed.