I'm wondering how to force the destructor to only print 1 cout statement
mine prints all names
i made a pointer dynamic array of name and other variables and i did delete the array
but it prints all names inserted into the array
here's my code:
The thing about destructors is that when the object leaves scope, the destructor is called for every object. Hence why you're probably getting something like...
1 2 3 4
Good bye John
Good bye Sally
Good bye Bobby
If you want it to print out a specific name ONLY, you're going to need to add some logic of something along the lines of
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
if (name == "John")
cout << "Good bye " << name << endl;
delete  array;
//Or if you want it to print out the first name in the array...
cout << "Good bye " << array.name << endl;
The gist of this: You need to indicate somehow that you want only a specific condition to print out a destructor message.
I also added in the delete var_name because that should be in the destructor if you're calling a destructor (only if the array is dynamically allocated, otherwise a nondynamically won't need the delete operator).
The destructor gets invoked for each object that must be destroyed. If you have 5 objects in your array, then you're going to get 5 destructor calls when you delete the array. If you only want 1 print, then you'll have to move the print out of the destructor and up to where the delete is called on the array.
Remessage me Exculibar. I only hop on these forums every now and then, so I never had anyone PM me before. I'm only in my third semester of C++ so I can't guarantee I'll know what's going on in your code (hence a beginner being in a beginners forum, who knew?!)
@fun2code, Working like a charm!! thank you mate
Genius way :D, im sure there's another way editing my code but it require u to read the whole code and takes a lot of time but this is a great way to fix this problem :D
1 more thing, it doesnt print Good bye (name) in the last statement
Good bye (name)
how to make it the last one ?
Not sure I understand. Do you mean that "Good bye (name)" should display only when the last instance of a Person is destroyed?
If so, then one method would be to add a staticint instanceCount; variable to your Person class. Initialize it to 0, increment it in every constructor, decrement it in the destructor, then print your message when instanceCount == 0. This isn't bulletproof though. You could make it fail by creating more instances of Person after destroying all current ones.
You have created a bit of a tricky problem with your requirement.
Maybe the cout << "Good bye " << name << endl; code belongs in ~Student(), not ~Person(). Call getName() though since name is private in the base Person class.
I say get rid of that global variable string StuName;.