Currently I'm writing a little bit of code to practice what I've been studying in a tutorial online. In this code, i allocated some space using 'new' using a pointer to create class instances, and iterate through them to set their names. However, I can only delete them when the pointer is at the 0th position. Can someone explain if I'm thinking of this incorrectly or what the general rule for this is?
//HEADER FILE
#include <iostream>
using namespace std;
class Animal {
private:
string name;
int age;
public:
Animal(string name = "UNDEFINED", int age = 0): name(name), age(age) {cout << "Animal created" << endl;}
~Animal() {cout << "Animal killed" << endl;}
void setName(char name) {this->name = name;}
void speak() {cout << "My name is: " << name << ", and my age is: " << age << endl;}
};
//MAIN FILE
#include "Animal.h"
int main() {
char name = 'a';
Animal *animals = new Animal[10];
for (int i = 0; i < 10; i++, animals++, name++) {
animals->setName(name);
animals->speak();
}
animals -= 10;
delete[] animals;
return 0;
}
The deconstructor is only called when the line 'animals -= 10' is included, but not when it is omitted or when 10 is any other number.