I created a class book with some class properties such as name and author (nothing dynamically allocated), then I created a class library which contains dynamic book array (like book* set) and its size and some methods, so in library class I added to destructor a 'delete' operator to deallocate the memory of 'set', because set is a pointer, but in book class I only added some text like "Destructor was called" to understand whether all my books would be deleted after program execution or not.
And the main problem is that first I created 3 book objects and then I created a library object, where I added all my 3 books. And when I run my code, I see messages of library object destructor and only one book destructor except of 3, why does it happen? Does it really matter if destructor of non-dynamic objects is called or not? Because I know that it's a real problem if the destructor of dynamic objects is not called because it leads to memory leak, but what about my situation? Can someone please explain me how it actually works for local objects and dynamic in general. (I've just finished learning OOP so that's why I have some problems with understanding such things, also sorry for my poor English)
class book
{
private:
string title;
string author;
public:
book() { title = ""; author = ""; }
book(string n, string a) : title(n), author(a) {}
string getTitle() { return title; }
string getAuthor() { return author; }
book& operator=(const book& other)
{
title = other.title;
author = other.author;
return *this;
}
~book() { cout << "Destructor of book \"" << title << "\" " << "was called!\n"; }
};
class library
{
private:
book* set;
int size;
int ptr;
public:
library()
{
size = 2;
ptr = 0;
set = new book[size];
}
void append(book &a)
{
if(ptr < size)
{
set[ptr] = a;
ptr++;
}
else // here I am just treating it as a simple dynamic array, so if I run out of space, I create a new dynamic array with n*2 size
{
book* copy = new book[size*2];
for(int i = 0; i < size; i++)
copy[i] = set[i];
set = copy;
set[ptr++] = a;
size *= 2;
}
}
~library()
{
cout << "Destuctor of library was called.\n";
delete set;
}
};
int main()
{
book one("Harry Potter", "J. K. Rowling");
book two("The Little Prince", "Antoine de Saint-Exupery");
book three("The Secret garden", "Frances Hodgson Bumett");
library myLib;
myLib.append(one);
myLib.append(two);
myLib.append(three);
return 0;
}