1.

Solve : Class constructors and deconstructors?

Answer»

I've got something I can't find the answer on...

I've got myself a beginning C++ instruction book and it's introducing me to classes. OK, I get the main idea, and I'm capable of WRITING a class with several member objects, no problem. However, I don't understand the point of a constructor or a destructor. I know vaguely that a constructor sets the initial values of some of the private (or public) data, but what does the destructor do? It's rather frustrating. The excerpt from the book:

Quote

Whenever you declare a constructor, you'll also want to declare a destructor ... destructors clean up after your project and free any resources or memory that you might have allocated.

What?? How??Basically a destructor is code that is ran when you delete the object. If you're allocated any DYNAMIC memory for this object, for example, you will want to PUT the code that frees the memory in the destructor. You can put it anywhere really, as long as it gets done, but it's just neater and more organised in there.

But despite what that book implies, destructors don't do that automatically (ie without any code from you) so watch out!Oh, I get it. Thanks. So a class really is just organized functions around an object. That makes everything so much easier. See, in the examples, since it's just getting into classes, the "destructor" looks like this:

Code: [Select]Object::~Object
{
}
No lie.

LATER examples simply have a cout, like this:

Code: [Select]Car::~Car
{
cout << "A simple destructor" << endl;
}
So it didn't SEEM to make any sense.


Discussion

No Comment Found