I've created a class called MyInteger
, and I'm trying to create a copy constructor that will correctly make a separate copy of the memory pInteger
points to, and make pInteger
in the new object point to it. I need to overload the =
operator so that each of the two objects involved has its own separate copy of the memory that its own pInteger
points to.
MyInteger
specification:
class MyInteger {
public:
MyInteger(int);
MyInteger(MyInteger &);
~MyInteger();
int getMyInt();
void setMyInt(int);
MyInteger operator=(MyInteger&);
private:
int * pInteger;
};
MyInteger
implementation:
MyInteger::MyInteger(int i) {
pInteger = new int;
*pInteger = i;
}
MyInteger::MyInteger(MyInteger &obj) {
pInteger = new int;
pInteger = obj.pInteger;
}
MyInteger MyInteger::operator=(MyInteger &i) {
pInteger = new int;
pInteger = i.pInteger;
return i;
}
MyInteger::~MyInteger() {
delete pInteger;
}
int MyInteger::getMyInt() {
return *pInteger;
}
void MyInteger::setMyInt(int i) {
pInteger = new int;
*pInteger = i;
}
I'm pretty sure the problem is at least partially due to the fact that I'm reassigning pInteger
in the constructor and operator overload: pInteger = new int;
and then pInteger = obj.pInteger;
. I think the second assignment is nullifying the first assignment using new
, so I'm getting
pointer being freed was not allocated
because pInteger
was not correctly being dynamically allocated. Am I going in the right direction here? I'm not sure how to fix this, any help would be great.