February 29, 2012

C++ example for triangle area with the help of getter setter functions

#include <cstdlib>
#include <iostream>

//INCLUDING <iomanip> FOR setfill() function
#include <iomanip>

using namespace std;

//We are required to write a class.
//Which should have area, base and height private data members (real numbers).
//We are declaring class Fortrianglearea

class Fortrianglearea
{

//Private data members area, base and height of float type for fractions
private:
float area, base, height;

//Public section, default constructor methods declared
public:
Fortrianglearea();

//setter and getter functions to set base and height
void setBaseHeight(float,float);
void getBaseHeight();

//display method to display the results after calculation
void Display(int);

void CalaulateArea();

};

//User will input for 2nd object and input values would be set for the second object
void Fortrianglearea::setBaseHeight(float base, float height)
{
this->base = base;

this->height = height;
}

void Fortrianglearea::getBaseHeight()
{
cout << endl << “User input requried for the second object” << endl << endl;

cout << “Value of Triangle Base: “;
cin >> base;

cout << “Value of Triangle Height: “;
cin >> height;

cout  << endl << endl;
}

void Fortrianglearea::CalaulateArea()
{
this->area = (this->base * this->height / 2);
}

//A default constructor which will initialize all data members
//with values 2.5 and 2.5 for base and height
Fortrianglearea::Fortrianglearea()
{
this->base = 2.5;

this->height = 2.5;

}

//Display (public) method for displaying area after calculation
void Fortrianglearea::Display(int obj)
{
cout << “Object”<< obj <<“” << endl;
cout << “Input :”;
cout << setfill(‘*’) << setw(20);
cout << “base ” << base << “, Height ” << height << endl;
cout << “Area of Object ” << obj << “: “;

//using setfill() setw() and setprecision() as instructed
if(obj==1)
cout << setfill(‘*’) << setw(11) << area << endl;
else
cout << setfill(‘*’) << setw(11) << setprecision(1) << area << endl;

}

int main(int argc, char *argv[])
{
cout << “\t Area of Triangle” << endl;
cout << “\t —————-” << endl << endl;

//Required objects of the same class
Fortrianglearea obj1, obj2;

//Assigning values of base and height for the first object through setter function
obj1.setBaseHeight(2.5,2.5);

//Calculating area of triangle
obj1.CalaulateArea();

//telling the display function that this is object one, so text will be changed acoordingly
obj1.Display(1);

//object two is for user, so now calling getter function
obj2.getBaseHeight();

//Calculating area of triangle
obj2.CalaulateArea();

//telling the display function that this is object one, so text will be changed acoordingly
//and setprecision will work here too
obj2.Display(2);

system(“PAUSE”);
return EXIT_SUCCESS;
}

Last updated: March 19, 2014