-
A little clarification?
Hi All
I'm new to the boards and new to C++, so I've been going through the tutorials available here. I was just wondering if anyone could give me some clarification on the code in Lesson 12. Ideally a good description of what a Constructor and a deconstructor are, what the code that begins Computer::Computer() actually does, and a bit more insight into the structure required for them to function correctly. Any help appreciated!
Cheers
Dr Nick
-
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 :)
-
A constructor is a function used by a class to initialize variables (generally, to allocate memory). It's called when an object of a class is created in any form. The deconstructor is used to clean up memory (generally, to free allocated memory) and is called whenever the object is destroyed- goes out of scope is deleted, etc.