So I am trying to delete my member pointer m_memory as it points to an array of char. When I try to delete the array that m_memory points to using delete[] I end up triggering breakpoints. I tried initializing m_memory as a nullptr before using new but it still triggered the breakpoint. Just wondering what my error is.
Header File:
#ifndef FISH_H
#define FISH_H
#include <iostream>
class Fish {
public:
Fish(int capacity, std::string name);// Constructor
Fish(const Fish &other); // Copy Constructor
~Fish(); // Destructor
Fish &operator=(const Fish &other); // Assignment Operator
void remember(char c); // Remember c
void forget(); // Clears memory by filling in '.'
void printMemory() const;// Prints memory
std::string getName();
protected:
const char* getMemory() const;// Returns memory
int getAmount() const; // Returns amount remembered
int getCapacity() const; // Returns memory capacity
private:
std::string m_name;
char * m_memory;
int m_capacity;
int m_remembered;
int m_replace;
};
#endif
Implementation file:
#include “fish.”
Fish::Fish(int capacity, std::string name) {// Constructor
this->m_capacity = capacity;
if (capacity > 0) {
this->m_capacity = capacity;
}
else {
this->m_capacity = 3;
}
this->m_name = name;
this->m_memory = new char[this->m_capacity];
this->m_memory[this->m_capacity] = '\0';
for (int i = 0; i < this->m_capacity; i++) {
this->m_memory[i] = '.';
}
this->m_remembered = 0;
this->m_replace = 0;
}
Fish::~Fish() // Destructor
{
delete [] this->m_memory; //exception thrown, breakpoint triggered
}
Main:
#include "fish.h"
int main() {
Fish *nemo = new Fish(3, "nemo");
nemo->~Fish();
}
nemo->~Fish();should bedelete nemo;std::string?virtualand through the magic of polymorphism the correct destructors will be called regardless of whether operating on base classes or subclasses.