Constructor Initialisation Lists

Members can also be initialised using initialisation lists.

 

The members to be initialised are defined after the signature of the constructor, which is followed by a colon : and then specifying the members in a comma separated list with the passed in parameter(s) from the signature making up the parameter for the member being initialised:

 

Triangle::Triangle(int x = 45.45, int y = 12.34) : width(x), height(y) {} ;

 

equivalent to:

 

Triangle::Triangle(int x = 45.45, int y = 12.34) {

width = x ;

height = y ;

} ;

 

#include <iostream>
using namespace std ;

class Triangle {

private:
	float width ;
	float height ;

public:
	Triangle(float, float) ; //constructor prototype
	void setWidth(float) ;
	void setHeight(float) ;
	float getWidth() ;
	float getHeight() ;
	float area() ;
} ;

//constructor with initialisation list
Triangle::Triangle(float x = 45.45, float y = 12.34): width(x), height(y) {} ;

void Triangle::setWidth(float x){width = x ;}
void Triangle::setHeight(float y){height = y ;}
float Triangle::getWidth(){return width ;}
float Triangle::getHeight(){return height ;}
float Triangle::area(){return ((width * height) / 2) ;}

int main () {

	Triangle myDefault ;
	cout << "myTriangle width was set at " << myDefault.getWidth() << endl ;
	cout << "myTriangle height was set at " << myDefault.getHeight() << endl ;
	cout << "myTriangle area: " << myDefault.area() << endl ;

	Triangle myTriangle(16.73, 29.84) ;
	cout << "myTriangle width was set at " << myTriangle.getWidth() << endl ;
	cout << "myTriangle height was set at " << myTriangle.getHeight() << endl ;
	cout << "myTriangle area: " << myTriangle.area() << endl ;

	return 0;
}

Compile & Run:

myTriangle width was set at 45.45
myTriangle height was set at 12.34
myTriangle area: 280.427
myTriangle width was set at 16.73
myTriangle height was set at 29.84
myTriangle area: 249.612

Leave a Reply