Animal destructor

Animal Destructor

Create an Animal class with a single member: std::string species. Create a constructor that outputs which species of animal is created and a destructor that announces it's destruction.

Create and destroy instances of Animal with new and delete as well as letting it go out of scope to see the constructor and destructor outputs.

Example output:

Animal "salmon" created.
Animal "salmon" destroyed.
Animal "lion" created.
Animal "lion" destroyed.

Answer

#include <iostream>

class Animal {
public:
    std::string species;

    // Constructor
    Animal(const std::string _species) : species(_species) {
        std::cout << "Animal \"" << species << "\" created.\n" << std::endl;
    }

    // Destructor
    ~Animal() {
        std::cout << "Animal \""<< species <<"\" destroyed." << std::endl;
    }
};

int main() {
    {
        Animal temp_anim("salmon");
    } // Exiting scope and destroying `temp_anim`

    // Creating an Animal object
    Animal* myAnimal = new Animal("lion");
  
    // Deleting the Animal object to observe destructor output
    delete myAnimal;

    return 0;
}
Questions