CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Multiple contructors using function overloading

Previously we saw that C11 permits a single function 'name' to have multiple type-signatures - multiple functions with same name, but with different sets of parameters.

The same concept applies to class constructors - a class may have multiple constructors (each named after the class), that permits an instance of the class to be created and initialised in different ways:

#include <iostream>

class Point {
public:
    double x, y;

    Point(void) {
	x = 0.0; y = 0.0;
	cout << "default constructor" << endl;
    }

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

int main(void)
{
    Point p; // default constructor
    // p.x is 0.0, p.y is 0.0

    Point q(2.0, 3.0); // 2-parameter constructor
    // q.x is 2.0, q.y is 3.0
}

 


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