Monday, February 23, 2009

Initalization of objects

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.


Author : Dhawan

0 nhận xét:

Post a Comment