Will someone please tell me what is wrong with this code? The program just runs and crashes.
Consider how the program is executed line by line:
You create an object of class book
. Since it was default initialized, the default constructor will be called. The default constructor allocates 10 instances of book
. Since those instances were default initialized, their default constructor is called. During the execution of the constructor of the first object, an array of 10 book
instances is allocated. Since those instances were default initialized, their default constructor is called. During the execution of the constructor of the first object, an array of 10 book
instances is allocated. Since those instances were default initialized, their default constructor is called. During the execution of the constructor of the first object, an array of 10 book
instances is allocated. Since those instances were default initialized, their default constructor is called. During the execution of the constructor of the first object, an array of 10 book
instances is allocated. ...
Can you see the problem? You have an ininitely recursive function that will not stop until it has taken all of stack space, at which point the program crashes. Such crash is called a "Stack Overflow".
Another wrong with the code that's not related to the crash: You never delete the memory that you allocated. It is a bad idea to use a bare pointer to dynamically allocated memory.
To create a tree structure with multiple children, I suggest following:
class books {
std::vector<books> arr;
// no constructor
};
This way, you won't leak memory, and you get to have leaf instances with no children, so there is no infinite recursion.