Some doubts with destructors and delete

Hi, I'm new to this website and c++, and I've been searching around information but could't find any that would clear my doubts. I'm sorry if someone already talked about this, is just that I have a project to do and is due in 2 days.

I know is kind of a must to pair a delete with every new, like:

void function(){
Classtype* ptr = new Classtype;
//code here...
delete ptr;
But in a case it's used like this(not using new), does it have to be deleted?

void function(){
Classtype C;
Classtype* ptr;
ptr = &C;
delete ptr; //Is this needed?

Another doubt is, if it were inside main() should I use a destructor with the deletes in the implementation instead? leave it as default? or just let the compiler use the implicit one created by itself?

I'm sorry for this stupid question is just that I'm having a hard time differentiating between delete and destructors and when to use what.

I'll appreciate any kind of information, and any kind of help that would make me a better programmer, thanks in advance!!

In most cases the destructor is automatically called when the object is destroyed.

There are two ways to manage the life of an object.

(1) Explicitly new and delete it.

(2) With a local variable, where it is destroyed when it goes out of scope (usually at the end of the function).

In your case, C is a local variable that is automatically destroyed at the end of the function. You did not use new to create it.

Using a pointer to it does not change its behavior. It will still be destroyed at the end of the function. If you try to use the pointer to access it after that then it will not work. (Technically, it might, but that's like telling someone they can test drive a car you just sold to someone else. It might not be there by the time you get to the lot.)

Hope this helps.
Thanks a lot! that cleared my doubts about new and delete. About the destructor, if I have three classes one derived from the other in a escalated order, I know the destructor should be virtual but does it have to be called in main at the end? or the program automatically calls the destructors it needs at the moment of deleting?

I have three destructors with this format in every class, only the base class has the virtual on it

~Classtype(); //declaration

Classtype::~Classtype(){} //implementation

Do I have to write any Classptr-> Classtype::~Classtype(); at the end of main depending the class destructor corresponding to the pointers I have created?
Topic archived. No new replies allowed.