See above question.
See above question.
-Dean
See the answer below.
Constructors are used to allocate memory needed by the object and initialise data. Destructors are used to free memory, typically allocated by the constructor.
Hmm...
Constructors dont even really take up much memory.
-Dean
>Constructors dont even really take up much memory
I don't understand what you mean.
>>Constructors dont even really take up much memory.<<
Constructors aren't what take up the memory. The object is what takes up the memory. The constructor is just the name of the method used to create an instance of the object.
Hmmm.....
I'm still not seeing the point of them. Could someone just give me an idiot's guide to constructors?
-Dean
OK. Let's suppose you have an object for dealing with a lot of text - say a document.
Where is that object going to store the text? The answer is that it will allocate memory to do this.
When does it need to allocate the memory? Usually when the object is created.
So where does it allocate the memory? Ideally in a method which is automatically called when the object is created. Such a method is a called a contructor.
What about freeing the memory once it's no longer needed? Yes this must be done, otherwise you'd have memory leaks.
So where should the memory be freed. Ideally in a method which is called just before an object is destroyed. Such a method is called a destructor.
First of all DeanDemon, do you know what's is Dynamically Allocating memory? and how to do it?
I think you'll be more able to understand constructors, but evern if you don't there are another uses that don't require dynamic momory allocation:
suppose you have that class and you created an objectCode:class RaionalNumber { public: private: int numerator; int denominator; };
;Code:RationalNumber r1;
it won't be initialized, and you cann't initialize.
but if you have a constructor:
so you can creat objects like this:Code:class RaionalNumber { public: RationalNumber( int x=1, int y=1 ){ numerator = x; denominator = ( y != 0 ? y : 1 ) } private: int numerator; int denominator; };
[code]
RationalNumber r2(1, 2); //numerator=1, denominator=2...
But again constructors are more useful when dealing with pointers and dynamic memory allocaion.
Did you get the point
none...