C++ Programming : Constructor

This tutorial will show you how to use struct to create a constructor in C++. We assume that you have already done the previous tutorial.


Constructor

You can use class or struct to create a constructor. The general format is :

struct name_of_constructor

{

// declare the variables here

name_of_constructor() { } // create empty constructor

~name_of_constructor() { } // create destructor

};

Suppose we want to create a constructor to handle 2D data type which contain coordinate X and Y. Write this code in your .cpp.

// create a constructor to handle coordinates 2D
struct Point2D
{
// declare local variable coordinate X and Y
int X;
int Y;
// create an empty constructor
Point2D() { }
// create a constructor to fill Point2D data type
Point2D(int x, int y)
{
X = x;
Y = y;
}
// create a desctructor to destroy Point2D data type
~Point2D() { };
};
// main function
int main(int argc, char** argv)
{
int key;
// create a Point2D data type named point
// insert X = 2 and Y = 3
Point2D point(2, 3);
// read the value
cout << “The coordinate is P(“ << point.X << “,” << point.Y << “)\n”;
cout << “\nArray\n”;
// create an array of Point2D data type
Point2D* arrayPoint = new Point2D[10];
// fill the array of point using for loop
for (int i=0; i<10; i++)
{
arrayPoint[i] = Point2D(i, i);
cout << “The coordinate in P” << i << “is (“ << arrayPoint[i].X << “,” << arrayPoint[i].Y << “)\n”;
}
// don’t forget to destroy the array if it is not used
delete[] arrayPoint;
cout << “\nVector\n”;
// create vector of Point2D data type
vector<Point2D> listPoint;
// fill the vector of point using for loop
for (int i=0; i<10; i++)
{
listPoint.push_back(Point2D(i, i));
cout << “The coordinate in P” << i << “is (“ << listPoint[i].X << “,” << listPoint[i].Y << “)\n”;
}
// don’t forget to empty the vector if it is not used
listPoint.clear();
cin >> key;
return 0;
}

The result is :

structure