operator+ overload returning object causing memory leaks, C++
- by lampshade
The problem i think is with returing an object when i overload the + operator. I tried returning a reference to the object, but doing so does not fix the memory leak. I can comment out the two statements:
dObj = dObj + dObj2;
and
cObj = cObj + cObj2;
to free the program of memory leaks. Somehow, the problem is with returning an object after overloading the + operator.
#include <iostream>
#include <vld.h>
using namespace std;
class Animal
{
public :
Animal() {};
virtual void eat() = 0 {};
virtual void walk() = 0 {};
};
class Dog : public Animal
{
public :
Dog(const char * name, const char * gender, int age);
Dog() : name(NULL), gender(NULL), age(0) {};
virtual ~Dog();
Dog operator+(const Dog &dObj);
private :
char * name;
char * gender;
int age;
};
class MyClass
{
public :
MyClass() : action(NULL) {};
void setInstance(Animal &newInstance);
void doSomething();
private :
Animal * action;
};
Dog::Dog(const char * name, const char * gender, int age) : // allocating here, for data passed in ctor
name(new char[strlen(name)+1]), gender(new char[strlen(gender)+1]), age(age)
{
if (name)
{
size_t length = strlen(name) +1;
strcpy_s(this->name, length, name);
}
else name = NULL;
if (gender)
{
size_t length = strlen(gender) +1;
strcpy_s(this->gender, length, gender);
}
else gender = NULL;
if (age)
{
this->age = age;
}
}
Dog::~Dog()
{
delete name;
delete gender;
age = 0;
}
Dog Dog::operator+(const Dog &dObj)
{
Dog d;
d.age = age + dObj.age;
return d;
}
void MyClass::setInstance(Animal &newInstance)
{
action = &newInstance;
}
void MyClass::doSomething()
{
action->walk();
action->eat();
}
int main()
{
MyClass mObj;
Dog dObj("Scruffy", "Male", 4); // passing data into ctor
Dog dObj2("Scooby", "Male", 6);
mObj.setInstance(dObj); // set the instance specific to the object.
mObj.doSomething(); // something happens based on which object is passed in
dObj = dObj + dObj2; // invoke the operator+
return 0;
}