initalization of objects

This tip submitted by mohit dhawan on 2005-09-16 10:36:46. It has been viewed 41616 times.
Rating of 5.6 with 185 votes



Whenever you have a pointer as a member variable in a class you should always use
your own (overloaded) version of = operator rather than the implicit one.

Not doing the above is a logical error. Why is this? Let's say that I have
class Abc
{
   int *p;
};


Now, say I have

Abc a,b;
a=b;


Here both the pointers of object a and b
will point to the same location; if the values stored in the address pointed to could be different for each object, this is a problem: change one object, and you change the other. (And if you have a destructor that frees the pointer, this is even worse!)

So next time you use a pointer in your class be sure two overload the assignment operator.



More tips

Help your fellow programmers! Add a tip!