ok take this class, might be like a Point class respresenting coordinates:
Code:
class Example
{
public:
Example( ); //default constructor, no arguments
Example( int x, int y ); //overload constructor takes 2 arguments
~Example( ); //destructor, you can only have 1 of these
private:
int* a; //using pointers by way of an example
int* b;
};
The constructors initialise data and request storage if needed (as in this case). The destructor is largely used to free up memory which has been dynamically allocated.
So the class above might look like this:
Code:
//default constructor, set both ints to 0- now we can declare Example objects as you would any other data type
Example::Example( )
{
a = new int; //allocate space
if( a == NULL )
{
cout << "Insufficent memory\nProgram exiting....";
exit( 0 );
}
*a = 0;
b = new int;
if( b == NULL )
{
cout << "Insufficent memory\nProgram exiting....";
exit( 0 );
}
*b = 0;
}
//overloaded constructor, now we can do this - Example eg( 10, 100 );
Example::Example( int x, int y )
{
a = new int; //allocate space
if( a == NULL )
{
cout << "Insufficent memory\nProgram exiting....";
exit( 0 );
}
*a = x;
b = new int;
if( b == NULL )
{
cout << "Insufficent memory\nProgram exiting....";
exit( 0 );
}
*b = y;
}
//destructor, releases memory if it is being used - very important,
//called automatically at the end of an objects scope
Example::~Example( )
{
if( a != NULL ) //space has been allocated
{
delete a; //return the memory used to the OS
}
if( b != NULL )
{
delete b;
}
}
If you look at C programs they use structs with init() and deInit() type functions to achieve almost the same effect. Those function have to be called manuallly though whereas constructors/destructors are called automatically.
I really hope that helps, took me bloody ages to type