Best practices of c++ - initalization of objects?

0 votes
asked Dec 22, 2013 in C++ by Tim
Hi all

  Best practices of c++ - initalization of objects?

1 Answer

0 votes
answered Dec 22, 2013 by anonymous

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;

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.