I've got a homework that requires me to have a repository of dogs. I have to have a dynamic array, templated. For some reason, I get a lot of memory leaks and I don't know where they are from. I've tried using Deleaker but it says "Unknown" at source file.
To be honest, I don't actually understand where I should deallocate memory since I can't use delete
.
This is my dynamic array definition and declaration (not all of it, just until the destructor), if it helps.
template <typename T>
class DynamicVector
{
private:
T* elems;
int size;
int capacity;
public:
// default constructor for a DynamicVector
DynamicVector(int capacity = 10);
// copy constructor for a DynamicVector
DynamicVector(const DynamicVector& v);
~DynamicVector();
DynamicVector& operator=(const DynamicVector& v);
};
template <typename T>
DynamicVector<T>::DynamicVector(int capacity)
{
this->size = 0;
this->capacity = capacity;
this->elems = new T[capacity];
}
template <typename T>
T& DynamicVector<T>::operator[](int index)
{
return this->elems[index];
}
template <typename T>
DynamicVector<T>::DynamicVector(const DynamicVector<T>& v)
{
this->size = v.size;
this->capacity = v.capacity;
this->elems = new T[this->capacity];
for (int i = 0; i < this->size; i++)
this->elems[i] = v.elems[i];
}
template <typename T>
DynamicVector<T>::~DynamicVector()
{
delete[] this->elems;
}
template <typename T>
DynamicVector<T>& DynamicVector<T>::operator=(const DynamicVector<T>& v)
{
if (this == &v)
return *this;
this->size = v.size;
this->capacity = v.capacity;
auto aux = new T[this->capacity];
delete[] this->elems;
this->elems = aux;
for (int i = 0; i < this->size; i++)
this->elems[i] = v.elems[i];
return *this;
}
Should I define a destructor in Dog.h
and Dog.cpp
also? Or in my dog repository (that uses the dynamic vector)?
Edit with dog class and repository:
class Dog
{
private:
std::string breed;
std::string name;
int age;
std::string photograph;
public:
// default constructor for a dog
Dog();
// constructor with parameters
Dog(const std::string& breed, const std::string& name, const int& age, const std::string& photograph);
// returns true if two dogs have the same name
bool operator==(const Dog & d);
//returns the breed
std::string getBreed() const { return breed; }
//returns the name
std::string getName() const { return name; }
//returns the age
int getAge() const { return age; }
//returns the photograph
std::string getPhotograph() const { return photograph; }
void setName(const std::string& n);
void setAge(const int& a);
void show();
};
class Repository
{
private:
DynamicVector<Dog> dogs;
int current;
public:
/*
Default constructor.
Initializes an object of type repository.
*/
Repository();
/*
Adds a dog to the repository.
Input: d - Dog.
Output: the dog is added to the repository.
*/
void addDog(const Dog& d);
//I have more methods here but they are irrelevant
}
As you can notice, I only have constructors in these classes so maybe that's the problem, considering the rule of three.