C++: Constructors and Destructors
In this lesson we will cover constructors and destructors.
Constructors
The most basic type of constructor is the default constructors, As you may have guessed this is what happens if no arguments are passed to the class member. For example lets say you have the program from the previous lesson 'Simple Classes':
#include <iostream>
class Ball
{
public:
int size;
double bounciness;
};
int main(){
using namespace std;
Ball MyBall = {5, 9.32};
cout << "Size: " << MyBall.size << endl;
cout << "Bounciness: " << MyBall.bounciness << endl;
system("PAUSE");
return 0;
}
But we replace this line:
Ball MyBall = {5, 9.32};with this:
Ball MyBall;
You will see when you run the application that the ball takes on strange numbers for its properties which we don't want.
To stop this from happening we use a class default constructor which has no arguments (as you call MyBall without any arguments to get the strange numbers). You create a default constructor like so:
Classname(){
//Default stuff here
}
With the case of the ball we might want a default constructor like this:
Ball(){
size = 0;
bounciness = 0.0;
}
Here is an example of a coordinate application which uses some constructors (to create constructors other than default simply add arguments into the brackets(you will see examples of this in the application)):
#include <iostream>
class Point
{
public:
Point(){
X = 0.0;
Y = 0.0;
}
Point(double X2, double Y2){
X = X2;
Y = Y2;
}
Point(double OneEntry){
X = OneEntry;
Y = OneEntry;
}
void Print(){
using namespace std;
cout << "(" << X << "," << Y << ")" << endl;
}
double X;
double Y;
};
int main(){
Point DefaultConstructorExample;
DefaultConstructorExample.Print();
Point Coord(4.2, -5.3);
Coord.Print();
Point CoordTwo(2.7);
CoordTwo.Print();
system("PAUSE");
return 0;
}
DownloadFrom reading this you should now know how to use constructors.
Destructors
A class can only have one destructor which it will call after a class has stopped being used. This is an example of a destructor with the ball application:
#include <iostream>
class Ball
{
public:
int size;
double bounciness;
~Ball(){
std::cout << "DESTRUCTOR!!!LOOK AT ME!!" << std::endl;
}
};
int main(){
using namespace std;
Ball MyBall = {5, 9.32};
cout << "Size: " << MyBall.size << endl;
cout << "Bounciness: " << MyBall.bounciness << endl;
system("PAUSE");
return 0;
}
DownloadThis would display:
Size: 5
Bounciness: 9.32
DESTRUCTOR!!!LOOK AT ME!!
It might take a while for you to see the destructor in the window (try running it through a couple of times) as it only displays after the system pause is over, and the application is actually closing.
Back to C++

