Hi
I created a class,simplified class is like below:
#include<iostream.h>
class cCat
{
public:
//Constructors and Destructors
cCat();
~cCat();
//Accessor Function
int & cCat::GetAge() const{ return *itsAge;}
//Convertion operator
cCat(int); // cCat object =int x
private:
int *itsAge;
};
cCat::cCat()
{
itsAge = new int;
*itsAge= 20;
}
cCat::~cCat()
{
}
//Convertion Operator
cCat::cCat(int Age)
{
itsAge= new int;
*itsAge=Age;
}
main()
{
cCat MyCat(23);
cout<<"My Cat age:"<<MyCat.GetAge();
MyCat=42; //this makes a memory leak
return 0;
}
As the code shows MyCat(23) and MyCat=42 statements have the same definition in the class and this makes a memory leak.(cause without deleting previous allocated memory I allocate a new memory in cCat(int Age)
so,how can I avoid this memory leak?