Constructors and destructors are one of the things in C++ that make objects more complicated. You'll understand this once you take on a large assignment that requires the use a many objects.
Constructors are "automatically" called when a new instance of the object is initialized. Like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
class myclass{
public:
myclass(const int& i)
{
this->a_number = i; //i is not initialized, so initialize it
}
~myclass()
{
a_number = 0; //for the sake of explanation
}
private:
int a_number;
};
|
The constructor sets the value of
a_number
for the first time in the instance of that object. Example:
myclass an_object(5); //an_object::a_number is now equal to 5
The constructor set the member variable, because it was executed upon initialization of that instance.
Constructors and destructors are basically functions that are executed when an instance of the class is created and destroyed. You can not call them.
when the scope of the class ends, or it is destructed (using
delete
on a pointer to an instance of the class will call the destructor before deallocating memory), the destructor is called. In this case, the destructor will set the integer member in
myclass
to 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
void demonstration()
{
myclass an_instance(4);
//whatever...
//before the function ends, the destructor is called. You don't need to do anything.
}
int main()
{
void demonstration();
/* myclass was initialized and destructed! :) */
return 0;
}
|
If you have any questions, feel free to ask.
Also, one more thing: When handling pointers, remember that when you call
delete
, you are deleting what that pointer points to, NOT the pointer itself. The pointer is still valid, but it will point to empty/unallocated space. Set them to
NULL
after deleting if you plan on referencing them afterwards (so you know whether they are allocated/deallocated).
Examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int *myint = NULL; //nothing in there...
int a_number(5); //a_number.
myint = &a_number; //myint points to a_number. You don't want to delete this!! The destructor of myint will do it for you
(*myint)++; //parentheses for emphasis on operator precedence
//a_number is incremented
myint = new int(10); //allocated space for a new integer. not you WILL want to delete it.
*myint = a_number; //this new number is set equal to the value of a_number.
delete myint; //delete the allocated space.
myint = NULL; //make sure we know it was deleted if we want to use the pointer again.
myint = &a_number. //doesn't matter in the slightest. Memory is stored at a_number and will be deleted upon it's destruction.
|
I hope you understand pointers a bit better.