constructors are simply a method (with the same name as the class) which is called when an object is created. This method can take parameters just like any other method or not take any at all. If it takes parameters, these parameters are usually used to set the object up into a known "state". That is, the object is setup with values.
Destructors (shown with a tilde and again the same name of the class) as you can imagine are the method that gets called when an object is destroyed. These do not take parameters and are used to "free up resources or other types of cleanup on the object prior to being deleted.
cpp
// Class declaration. Has one constructor which can have no parameters.
// It also has a destructor.
class example {
public:
example();
~example();
};
// Class implementation for these two functions.
example::example() {
cout << "You created an object!" << endl;
}
example::~example() {
cout << "You destroyed an object!" << endl;
}
Now when you go to create an object, it will automatically call the constructor method. When you destroy the object it will automatically call the destructor (if one is defined).
cpp
// This will print out "You created an object!"
example *ex = new example();
// This will then print out "You destroyed an object!"
delete(ex);
Some rules to remember with constructors...
1) They are the same name as the class
2) They don't have return types (not even void)
3) You don't have to write one yourself, but the compiler always puts one in and is known as the "default constructor". It is empty.
4) Related to point 3, if you do create a constructor that takes parameters, then you MUST provide a default empty constructor because then the compiler will not add it for you and you have to have one for a class.
5) Use constructors to setup member variables for the object only and try to keep it short as possible. Great things for constructors include initialization of variables, creation of inner objects, setting of pointers etc.
Things not good in constructors... variables of other classes, calls to long unneeded functions, anything that depends on some other class or environment being set.
You can find more explanation and examples at the link below...
Classes Tutorial (scroll down to constructors and destructors)Enjoy!