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 ;

} ;

 

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