Hi Guys,
Do we have to define a destructor when making a class or the destructor is called automatically when we destroy any object?
Hi Guys,
Do we have to define a destructor when making a class or the destructor is called automatically when we destroy any object?
What book are you using to learn C++?
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Well I was using a book but I lost it ,it was by Deitel (I don't remember the name of the book).
But now I just use links on internet to study about C ++ language.
I actually wanted to know that what is the use of writing a destructor in a class if it is called automatically
and destroys the object?
Last edited by student111; 06-22-2012 at 02:35 AM. Reason: adding more
Ah. Well, since you lost it, you might as well get a new one. Accelerated C++ should be fine especially since you already have some C++ knowledge.Originally Posted by student111
A good introductory book on C++ would explain this to you at some point.Originally Posted by student111
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
The compiler will always call the destructor when an objects lifetime ends.
If you don't provide a destructor then the compiler will generate one automatically. This is the ideal situation; you just let the compiler take care of it.
However, if your object has things that it must clean up itself, then you will need to provide a destructor to take care of those things.
Read about "The Rule of Three (C++)"
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
There's a limit to what the compiler can do automatically for you. For example, it'll automatically call the destructors for any member classes of your class - it knows what members your class has at compile time.
There's plenty the compiler can't possibly know. Most common is freeing dynamically allocated memory -- often you'll want to free what you've used. Other common examples from the net: opened files, sockets, database connections.... you have to shut down such things, as you can't possible expect the compiler to know how. I don't really like those examples -- I think the simpler the better.
If you need stuff done whenever a class instance is destroyed, it goes in the destructor.
If you've written your own destructor, it's still automatically called and all of the automatic stuff still happens automatically. You just add to it when you need to.