Constructors with parameters

It is possible to have as many constructors as you like as long as their signatures are different, and are therefore being overloaded.

 

This allows your parameters to be set at instantiation, rather than a default set.

 

#include <iostream>
using namespace std ;

class Triangle {

private:
	float width ;
	float height ;

public:
	Triangle() ; //default constructor prototype

	Triangle(float x, float y){ //overloaded constructor
		width = x;
		height = y;
	}

	void setWidth(float) ;
	void setHeight(float) ;
	float getWidth() ;
	float getHeight() ;
	float area() ;
} ;

Triangle::Triangle(){ //default constructor definition
	width = 45.45 ; 
	height = 12.34 ;
}
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(22.22, 31.13) ;
	cout << "myDefault width was set at " << myDefault.getWidth() << endl ;
	cout << "myDefault height was set at " << myDefault.getHeight() << endl ;
	cout << "myDefault area: " << myDefault.area() << endl ;

	return 0;
}

Compile & Run:

myTriangle width was set at 22.22
myTriangle height was set at 31.13
myTriangle area: 345.854

 

 

The default constructor could now be placed within the parametrised constructor to simplify:

#include <iostream>
using namespace std ;

class Triangle {

private:
	float width ;
	float height ;

public:
	Triangle(float x = 45.45, float y = 12.34){ //default constructor
		width = x;
		height = y;
	}
	void setWidth(float) ;
	void setHeight(float) ;
	float getWidth() ;
	float getHeight() ;
	float area() ;
} ;

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(22.22, 31.13) ;
	cout << "myDefault width was set at " << myDefault.getWidth() << endl ;
	cout << "myDefault height was set at " << myDefault.getHeight() << endl ;
	cout << "myDefault area: " << myDefault.area() << endl ;

	return 0;
}

Compile & Run:

myTriangle width was set at 22.22
myTriangle height was set at 31.13
myTriangle area: 345.854

Leave a Reply