I want to make many objects of type "Student" and store them so they can be used throughout the program. I'm also required to print out messages when a student is created and destroyed, but when i put the "destroyed" message in the destructor it'll appear whenever I change instance to create the next student cause the destructor is called. Is there a way to bypass that and only have the destructor be called for each object at the end of my program?
This current piece of code has each student destroyed whenever the next one is to be created (with each for loop), and then again "redestroyed" at the end of the program. I only want them to be deleted at the end.
#include <iostream> #include <string> class Student{ // members public: Student(){} Student(std::string name, int floor, int classroom ){ std::cout<<"Student created\n\n"; // assignments } ~Student(){std::cout<<"Student destroyed\n\n";} // methods }; int main(int argc, char** argv) { Student* S=new Student[5]; for (int i=0; i<5; i++){ S[i]=Student("example", 1,1); //makes 5 students and stores them } // rest of the program delete[] S; return 0; }
S[i]=Student("example", 1,1);creates a temporary object of typeStudent, initialised using the arguments"example",1, and1, assignsS[i]to become a copy of the temporary, and destroys the temporary.newanddelete- try learning how to do THAT before worrying about how often destructors are called. It will make it easier, in a lot of cases, to avoid unnecessary construction and destruction of objects.