Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: Class constructors and deconstructors  (Read 2935 times)

0 Members and 1 Guest are viewing this topic.

Dilbert

    Topic Starter
  • Moderator


  • Egghead

  • Welcome to ComputerHope!
  • Thanked: 44
    Class constructors and deconstructors
    « on: December 27, 2006, 02:51:46 PM »
    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??
    "The geek shall inherit the Earth."

    Neil



      Expert
    • Fear me Track. Noone can escape my wrath.
    • Thanked: 3
      Re: Class constructors and deconstructors
      « Reply #1 on: December 28, 2006, 03:57:23 AM »
      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!
      « Last Edit: December 28, 2006, 03:58:31 AM by Neil »

      Dilbert

        Topic Starter
      • Moderator


      • Egghead

      • Welcome to ComputerHope!
      • Thanked: 44
        Re: Class constructors and deconstructors
        « Reply #2 on: December 28, 2006, 01:00:11 PM »
        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. :)
        "The geek shall inherit the Earth."