Constructors and Destructors

Started by benthehutt, March 30, 2005, 05:15:20 PM

Previous topic - Next topic
I'm trying to learn C++, and I've been doing pretty good, but I think  I need some help with constructors and destructors.

First of all, I know constructors are called when you create an instance of a class(Like an int named sally), but when are destructors called?  I don't get when they go out of scope.  

Like, if you make a new instance of a class in int main(), does the destructor get called immediately or at the end of it, or when you call a function that's not a method of the class...

I'm confusing myself...

Also, I'm using Bloodshed Dev 4.9.9.2, is that a good one, or should I fork some money over for a better one? (I'm really new to C++)
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.

I only do C I'm afraid.

One person that might be able to help some is godaigo. I believe he knows C++.

I suppose I could find some documents, but wouldn't know what to look for, because object orientied stuff isn't what I enjoy.

I'm trying to remember if I can think of any documents that are C++ related instead of C but I  just can't think of any. I'm sure you tried googling this a bit ?

"My Terminal is my Soul"

Google wasn't too much of a help.  All the stuff was about what constructors and destructors were, nothing about when they're called.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.

btw, why do you hate OOP?  I love it like so many fine cuban cigars...  C sucks next to C++(that's why it's ++).
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.

I guess I'm old fashioned. I hate OOP, the look, the feel, everything. Besides, if I needed to do it, it is possible in C (though I guess most don't know that). I don't know... just hate OOP. It's the one reason I dislike Java too.

Either way.. C is more portable and is more supported for what I do. Sure there are many programs that are in C++ but many of them are in C too and it's been around a lot longer. And since my code is all text anyway, no need for Objects. I imagine in X the code would be more often in C++ but since I don't use X... well you get the idea.

As for C being inferior, I would hardly think it's inferior... it's simply different (much like the OS wars etc).

"My Terminal is my Soul"

I just caught this thread, let me crack the rust off of my brain. I have a great little tutorial about nothing but constructors and destructors hanging around somewhere (unless it's in storage), but I'll dig up what I can (unless someone beats me to it).

As far as OOP goes, I think that I probably fall somewhere between the two of you :) I think it definately has it's uses, but there are times I really prefer to just do a straight procedural program. Oh well, to each his own.
Godaigo
All's fair in Love and Brewing.

So the basic premise (as I'm sure you know) of the destructor is to deallocate the resources that you allocated by using the constructor to intialize the instance of the class (sally to use your previous example). Basically the destructor (has the same name as the class with a tilde "~" (logical NOT operater in C++) in front of it (i.e. ~main) ) allows the class to clean up after itself automagically. Let me give you an example of code for a class (since I'm at work I took this from C++ for Dummies which was laying around for some reason (the tutorial I was talking about is from an academic text):
Code  cpp Select
#include <iostream.h>
class Student
{
    public:
       Student()
        {
          cout << "constructing student\m";
          semesterHours = 0;
           gpa = 0.0;
        }
    ~Student() //the destructor
        {
         cout << "destructing student\n"; }
        //...other public members
    protected:
         int semesterHours;
         float gpa;
};

class Teacher
{
   public:
     Teacher ()
      {
         cout << "constructing teacher\n";
      }
     ~Teacher()
      {
         cout << "destructing teacher\n";
      }
};
class TutorPair
{
   public: 
      TutorPair()
      {
         cout << "constructing tutor pair\n";
          noMeetings = 0;
      }
     ~TutorPair()
      {
          cout << "destructing tutor pair\n";
      }
    protected:
       Student student;
       Teacher teacher;
       int noMeetings;
};

int main(int argcs, char* pArgs[])
{
   TutorPair tp:
    cout << '"back in main\n";
    return 0;
}
So assuming that I typed the code in correctly (hah) the output would look like this:

constructing student
constructing teacher
construction tutor pair
back in main
destructing tutor pair
destructing teacher
destructing student

The construtor for TutorPair is invoked at the declaration of tp, in main() and the destructor at the closing bracket of main(). So basically when you put the destructor into your class it will automatically deallocate those resouces when necessary. Personally I found that unless doing programs with a lot going on (basically beyond the scope of an introductory type of class) that these weren't terribly necessary, but without them you can definately get yourself in trouble. Let me know if that helped at all or if you have any other questions (or if you couldn't follow the code I typed in!) Cheers....  ::)
Godaigo
All's fair in Love and Brewing.

A website ( I believe it's hosted by O'Reilly) with some C and C++ resources is: http://www.techbooksforfree.com/ccpp.shtml
although I haven't looked at most of the resources myself. Cheers...
Godaigo
All's fair in Love and Brewing.

I didn't mean to burst your bubble, Metgod, but I thought the entire point of C++ was to one up C...

Anyway, I don't do everything object oriented, I agree that procedural programming does have its uses in the world (I still love batch!).  Everytime I think of that, my brain drifts off to the days of Qbasic and the game with the monkeys and explosive banannas... ::)
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.

Thx Godaigo, you rock!  (You guys know eRthing)

Anyway, as to the code, I'm a bit confused.  I understand how the constructor of tp gets called, but I don't get how all the other ones are called.

I thought you had to make an instance of each class, like Teacher Sally, Student Humphrey to invoke the constructor.  In this code, none of the classes from which constructors are called are in int main().
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.

Only one more question (I forgot to add it to the last post):

Can you declare an instance of a class in a method of another class?

Like this:

________________________________________________________
Code  cpp Select
class cMakeThis{
     int x=5;
};

class cCrashTestDummy{
     public:
          void makeInstance();
     private:
          int testInt;
};

void cCrashTestDummy::makeInstance(){
     makeThis testClass;
}

int main(){
          blah blah blah, who cares...
}
_____________________________________________________

And if so, when is the destructor called?  At the end of that class's method, or at the end of int main()?

Plus, in your example you have in your class interface, 'public' and 'protected.'  Is this the accepted way, or is 'public' and 'private?'

Also, thx for the web-site...you're a genius!
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.

Wow you have a lot of questions ben! That's great, let's see I'll take the easy one's first. As to the private protected thing, I actually have always used private (protected was the way the code was written in the example that I pulled from). I'm not sure about the method question off the top of my head, I've been doing C for last year or so and no C++. I'll check on it. As far as the destructor in the example it's being called automatically at the end of main(). I seem to recall that there was something wonky about trying to declare the instance of a class in a method of another class, but I'm not sure off the top of my head so I'll go and look it up!  ::) As to where the destructor would be called my guess would be at the end of main() as well, but like I said I'll double check that. I'm at work still, so I'll get back to you tomorrow! Cheers... and keep up the questions, you're making me refresh my knowledge base! As Tony the Tiger says "That's GRRREAT!"
Godaigo
All's fair in Love and Brewing.

I can't believe I just quoted Tony the Tiger, I need some sleep.... or a pint!
Godaigo
All's fair in Love and Brewing.

No problem.

It's true, the ++ is increment by one. But, I still prefer C. And the way I look at it, C is what Unix and Linux are in, not C++. My personal opinion is that C++ is bloated (and I know I'm no the only one to think that). But of course that's my opinion and not necessarily everyone's.

I just don't like the look and feel I guess. But I'm sure it has it's uses and it definitely has it's fans.


"My Terminal is my Soul"

I do have one more question, Godaigo.  When you make a variable, where in memory does it store the variable name?  Or does it?
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.

SMF spam blocked by CleanTalk