HFX Forum

Programming => C/C++ => Topic started by: benthehutt on March 30, 2005, 05:15:20 PM

Title: Constructors and Destructors
Post by: benthehutt on March 30, 2005, 05:15:20 PM
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++)
Title: Re:Constructors and Destructors
Post by: Metgod on March 30, 2005, 05:21:31 PM
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 ?

Title: Re:Constructors and Destructors
Post by: benthehutt on March 30, 2005, 05:29:28 PM
Google wasn't too much of a help.  All the stuff was about what constructors and destructors were, nothing about when they're called.
Title: Re:Constructors and Destructors
Post by: benthehutt on March 30, 2005, 05:32:37 PM
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 ++).
Title: Re:Constructors and Destructors
Post by: Metgod on March 30, 2005, 07:22:28 PM
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).

Title: Re:Constructors and Destructors
Post by: godaigo on March 31, 2005, 03:19:27 PM
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.
Title: Re:Constructors and Destructors
Post by: godaigo on March 31, 2005, 04:04:41 PM
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....  ::)
Title: Re:Constructors and Destructors
Post by: godaigo on March 31, 2005, 04:07:12 PM
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...
Title: Re:Constructors and Destructors
Post by: benthehutt on March 31, 2005, 07:15:44 PM
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... ::)
Title: Re:Constructors and Destructors
Post by: benthehutt on March 31, 2005, 07:23:59 PM
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().
Title: Re:Constructors and Destructors
Post by: benthehutt on March 31, 2005, 07:35:38 PM
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!
Title: Re:Constructors and Destructors
Post by: godaigo on March 31, 2005, 10:29:21 PM
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!"
Title: Re:Constructors and Destructors
Post by: godaigo on March 31, 2005, 10:29:59 PM
I can't believe I just quoted Tony the Tiger, I need some sleep.... or a pint!
Title: Re:Constructors and Destructors
Post by: Metgod on March 31, 2005, 11:40:54 PM
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.


Title: Re:Constructors and Destructors
Post by: benthehutt on April 01, 2005, 09:57:05 AM
I do have one more question, Godaigo.  When you make a variable, where in memory does it store the variable name?  Or does it?
Title: Re:Constructors and Destructors
Post by: benthehutt on April 01, 2005, 09:57:32 AM
Yay for C++!! ;D
Title: Re:Constructors and Destructors
Post by: godaigo on April 01, 2005, 04:40:56 PM
All right I'll take a stab at this stuff again. As for where the variable name is stored, I actually don't remember (and I know I have a reference that would tell me, but I don't have it handy, it's in storage) unless it's stored as part of the actual byte string of the variable value??? Not really sure though, sorry....  Oh and as to why the destructor's and constructor's work without more to them is that they all function at the compiler level and how they're declared within the class allow the compiler to recognize them and thus execute their actions. Also remember that destructors are called in the reverse order of any constructors called. Allright, I did a little research and it looks like you can declare an instance of  class in the method of another class. If you have a constructor defined for the class of the instance you are declaring it will use that, otherwise it will call the default C++ constructor which is binary 0. This happens after control passes to the constructor for the class you are currently in but before control passes to the first statement in that constructor (if that makes sense). So the instance would be set by its constructor before the constructor of the method you were declaring set it's instances. (I hope that's not too confusing). My feeling with the destructor is that the instance will be destructed at the end of main() due to the standard C++ compiler settings. However, there are some exceptions to this depending upon how you go about it. For instance, you couldn't pass data to that instance of the other class from within the constructor of the method itself because it already exists before the body of the constructor is executed. As with so many things in C++ there is a way around that, but I think that's more in-depth than I want to get on the boards, but it might be great for the teaching sight, eh Cobby! Now I will add the disclaimer that I am fairly rusty with this so if anyone else following the thread wants to tell me I'm on crack and totally wrong please due, I'm always up for learning new stuff myself! Cheers.... :)
Title: Re:Constructors and Destructors
Post by: godaigo on April 01, 2005, 04:43:25 PM
Here's a nice list of the order of Construction I found:
Local and static objects are constructed in the order in which their declarations are invoked.

Static objects are constructed only once.

All global objects are constructed before main().

Global objects are constructed in no particular order.

Members are constructed in the order in which they are declared in the class.

Destructors are invoked in the reverse order from constructors.

Hope that helps ben! Cheers....
Title: Re:Constructors and Destructors
Post by: benthehutt on April 05, 2005, 05:40:47 PM
Wow, that was alot of info at once.  Thanks godaigo, you da man!

I only have one more question, and I fear you'll laugh at it cause it's kind of stupid, but here it is:

can you return anything?  For instance (this may be stupid), can you say

return cClass returnClass;

If cClass is a class with no constructor?  Cause then, in my strange little mind, it would a return zero, because it would use the default constructor 0.

I think that's way off, but could it happen??? :o
Title: Re:Constructors and Destructors
Post by: godaigo on April 06, 2005, 05:21:06 PM
Hey ben, I'm glad that I'm being helpful. Like I said before, if anyone has better working knowledge of this please jump in! My basic understanding is that the constructor has no return type since it is called automatically, so if you tried to return something it would probably throw an error since there would be no memory allocated to hold the return value. I'm not positive of that though so I'm going to do some more reading and I'll let you know if I come across something else. I have a feeling and vague stirrings of memory that there is more to this than meets the eye. I'll post what I find out! Cheers....
Title: Re:Constructors and Destructors
Post by: benthehutt on April 06, 2005, 06:19:15 PM
Sorry if I'm bugging you with all of these questions, but you are really helpful.  Thanks for all the help... :)
Title: Re:Constructors and Destructors
Post by: godaigo on April 07, 2005, 02:39:45 PM
No problem, I have to say that although I've been on this board for a fairly long time (since before we transfered to this new format) I don't believe that I've really contributed anything (at least technically speaking), so if I'm doing that now that's awesome. So I'm actually waiting for parts (it's hard to get them in the frozen north sometimes) and my home compuker is down, but I'll see what I can come up with on your questions still. Cheers....
Title: Re:Constructors and Destructors
Post by: Metgod on April 07, 2005, 03:57:39 PM
You're still up there or have things there ? Damn.. I'd personally love to live in colder environment but not if it's because of what I remember you being there for (work or something I think).

When do you get everything back set up ?

Title: Re:Constructors and Destructors
Post by: godaigo on April 07, 2005, 04:57:19 PM
Actually my compuker's power supply just fried, so I had to order a new one and I'm just waiting for it to be delivered. I had to take slow shipping because they wanted twice as much for shipping as the case itself cost. Basically I'm up here for work and most of my stuff is in storage back down south with my parents. Speaking of work I have to get going, but I'll reply some more in another post! Cheers Metty!
Title: Re:Constructors and Destructors
Post by: Metgod on April 07, 2005, 05:56:46 PM
Ouch...

I got a computer a couple years ago and it's been junk ever since. I couldnt get it to work. So I get a new motherboard (quite pricey for me) and then I try to install the OS and it still bails out. It then hits me how stupid I was.. that it was probably ram. So I buy new ram and it works.. what a waste of money.

Was rather pissed at myself (this happened a week or two ago)... as money doesn't come easy to me.

Hope you get your PSU back soon.
Title: Re:Constructors and Destructors
Post by: godaigo on April 07, 2005, 09:16:14 PM
Yeah, I have to object on principle to paying $100 for shipping for a $45 power supply and case. Oh well.....
Title: Re:Constructors and Destructors
Post by: wilnix on August 14, 2005, 02:37:18 AM
BenTheHutt -

Did you get your question answered? Variable storage?


Let me know cuz I can help...

Wilnix
Title: Re:Constructors and Destructors
Post by: benthehutt on August 14, 2005, 03:46:22 PM
Well, I still don't really understand the whole "storing pi" thing, but no one had any idea how you could do that with any variable in C++.
Title: Re:Constructors and Destructors
Post by: wilnix on August 15, 2005, 01:44:27 AM
Yeah -


Read this: http://www.cs.berkeley.edu/~ejr/GSI/2000-spring/cs267/assignments/assignment1-results/flab/

Store that in memory? I don't think so...unless the word 'Cray' appears...


Thanks,

Will
Title: Re:Constructors and Destructors
Post by: benthehutt on August 15, 2005, 12:25:59 PM
I am thoroughly convinced that no cray on the face of this earth could even do that.  For one thing, 865 gigs of RAM doesn't come close to what they would need to store the number in RAM even once.  There's gotta be some other way for them to do it.  What they were using was an algorithm, which means that they do an operation over and over and over.  Even a cray can't move around a 206 billion digit number that fast.  Assuming they had enough RAM to store the number, clearing it out of RAM to put it back in for the next computation would take more than 30 minutes (which is the total time it took).
Title: Re:Constructors and Destructors
Post by: wilnix on September 04, 2005, 05:11:13 AM
variable names arent really stored, the name is like a human reference to an address in memory where the data is stored. You can find this by running a debugger on your code. I, like Metgod, still spend more time with C the C++, and I like to use gdb as a debugger. Other debuggers will show you this relation as well.

Good Luck!

Wilnix
Title: Re:Constructors and Destructors
Post by: Metgod on September 04, 2005, 10:37:19 AM
GMP is one way to store large numbers. As I said before, probably a library (just didn't know of any at that time). Of course, you still have the problem of memory, but it does make things a bit easier for some while ...

Check out the GNU MP BigNum Library at:

http://www.swox.com/gmp/

(And what Will says is quite true about variables and being stored. Ditto with debuggers [gdb is really nice but most can show you the same things (which happens to be loads of info!)])
Title: Re:Constructors and Destructors
Post by: benthehutt on September 10, 2005, 12:10:30 AM
String arithmetic!  Well, that's a very slow way of doing it, but I've found that it works.  The string arithmetic library can be used instead of numbers, it makes it actually possible to store that many numbers.

Also, I've found that there is also a very easy calculation that shows when the decimals stop converging.  That is, when the algorithm is going into more and more iterations, certain decimals stop changing.  So, you store these in something like a text file, and just work with the right part of the numbers.  Though the algorithm must be restated to do this.

I'm going to try writing a simple program to calculate pi using these methods.  I'll probably use ADA though.  It seems easier to do computational stuff in ADA than in C++.  (which is what I was going to write it in)  Though I might try both, who knows.

I'll post what I got when I get it.  (Though I might be preoccupied, hopefully I'll be starting a Beowulf cluster tommorrow!)
Title: Re:Constructors and Destructors
Post by: Metgod on September 10, 2005, 11:06:30 AM
Nice idea.

I'd be curious to see the string arithmetic library (or do you mean standard functions ?). So if there is a specific one, please share the name.

I'd guess you would need a library though, since the standards can only convert so many bits (like, strtoull would be for unsigned long long, etc.).
Title: Re:Constructors and Destructors
Post by: benthehutt on September 11, 2005, 11:28:40 AM
Oh no, it's not an actual library, I have to write it.  It's just one way I'm thinking of doing it.  I think I've got a better idea though, a guy I know told me it would prolly be easier and more efficent to use bitwise arithmetic.  Two ways he suggested were to use the java.math.BigDecimal class, or a GMP-based library like MPFR.
Title: Re:Constructors and Destructors
Post by: Metgod on September 11, 2005, 06:54:10 PM
Sounds good.

Though, unless I misunderstand you, bitwise arithmetic still has the limitations of numbers capacities. But yeah, a library is probably one decent way to go. It's unfortunate systems are restricted by the architecture... What might be an idea is to check out a program that figures out pi and then see what they use. Then check another one, and gather around information.

String arithmetic might work, if you have a good algorithm to keep the limits in mind. You'd still have to have a way to keep track of numbers and even if it's a string, a larger string would be difficult to keep (or again, you have something else in mind, in which case I'd love to hear it).



Title: Re:Constructors and Destructors
Post by: benthehutt on September 11, 2005, 08:03:24 PM
I'm looking into a buttload of source from many different opensource projects.  One of the most promising projects looks to be here:

http://www.pislice.com/wiki/Main_Page

It's a distributed pj that is trying to break 1.24 trillion digits.  Wow.
Title: Re:Constructors and Destructors
Post by: Metgod on September 11, 2005, 09:08:37 PM
Neat (although I still don't know the point of that, except for the challenge).

I know you explained this before, but not being a math person, I tend to forget math things... isn't it kind of useless after so many decimal points ?

Or is this just for the fun ? I can see that definitely, but as far as usefullness, not sure ?

Anyway, keep us up posted on this one (your project).

Title: Re:Constructors and Destructors
Post by: benthehutt on September 12, 2005, 12:24:16 AM
Ha! You should read A Mathematicians Apology by Hardy.  Of course this is mostly useless.  5 decimal places can get a man to mars, 20 can predict the orbits of all the planets with more accuracy than we will ever need.
However, many methods and ideas have sprung up from calculating pi.  New areas of math have been discovered from it and mathematicians hope to find some sort of pattern in it.  (Though, truth be told, it's been proven that a pattern will never exist in pi)

For me it's purely for fun and for learning.  I'll get to learn more math and more programming.  As far as the whole digits record thing, that's just retarded, though it does give scientists a good list of 1.24 trillion random numbers when they need it...

mmmm.....math..... ;D
Title: Re:Constructors and Destructors
Post by: Metgod on September 12, 2005, 08:31:52 PM
I think I read an article (though it was on slashdot, hehe) that says pi isn't all that random (or maybe it was the other way around).

Anyway, random numbers is another very interesting topic.

I think my favourite way is using the /dev/urandom device (or equivalent) on unix/linux based OS's. The C method really sucks .. and is anything but random (even resetting the seed with the time syscall doesn't do much).

Good RNGs are hard to find. I think that's the name of an article too (something like that anyway)... Lots of methods, but they aren't all the best I think (which is a real shame).

About pi.. I can understand your view though, even though I'm not a math person. Learning more and the fun and challenge. Sounds good to me.
Title: Re:Constructors and Destructors
Post by: benthehutt on September 12, 2005, 10:06:12 PM
Just to clarify:

Pi is not random at all, in fact it's so precise it must use an infinite amount of digits to be expressed correctly.  However, between any two digits of pi that are spaced pretty far apart, there are about the same amount of each digit 0-9.  That's why I said it was random.

Pi is so weird, who'd a thunk it.

RANDOM PI FACT:
Given a random river in the world (let's say, the Amazon for instance) measure the distance between the two farthest points of it (the top and the bottom).  Now put this number under the actual length of the river and as the river gets older and older, that ratio approaches pi.  So, theoretically, the ratio would be exactly pi with an infinitely old river.

I'm freaked out. :o
Title: Re:Constructors and Destructors
Post by: Metgod on September 13, 2005, 09:22:39 AM
That's a pretty neat fact...

And thanks for clarifying the randomness part, I was right then, about the page I read. Honestly couldn't remember 100% which way I read it though. But it must have been that it's not random.