CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Initialising the data members of a class with constructors

In most C11 programs, when introducing a new variable (often near the top of a block of statements) we immediately follow the introduction by multiple statements which initialise the variable.

#include <iostream>

MyVector vec;

vec.start.x = 0.0;
vec.start.y = 0.0;
vec.end.x   = 0.0;
vec.end.y   = 0.0;

Point p;

p.x         = 0.0;
p.y         = 0.0;

If a scalar variable, this presents little problem, but for structures or arrays, we must ensure that the initial value is 'suitable', and that we don't miss any values.

This is often achieved with an additional function, defined physically 'close' to the definition of the structure or array datatype.

In C++, as with most object-oriented languages, we can combine the class's fields (internal variables) with a method to initilise them. This special method, termed a constructor, doesn't require any 'external' code to have knowledge of the implementation of the class, or how its fields are initialised.

A constructor is a method that is called when a class instance is created.

#include <iostream>

class Point
{
public:
    double x, y;
    Point(void) {
	x = 0.0; y = 0.0;
	cout << "Point instance created" << endl;
    }
};

int main(void) {
    Point p; // Point instance created
    // p.x is now 0.0, p.y is now 0.0
}

#include <iostream>

class Point
{
public:
    double x, y;
    Point(double nx, double ny) {
	x = nx; y = ny;
	cout << "2-parameter constructor" << endl;
    }
};

int main(void) {
    Point p(2.0, 3.0); // 2-parameter constructor
    // p.x is 2.0, p.y is 3.0
}

 


CITS2002 Systems Programming, Lecture 23, p8, 17th October 2023.