Pages

Thursday, June 23, 2011

Constructor - Source Code

Problem :
Write a Circle class that has Radius a data member, also using a constructor that sets the radius value by set and get functions. Then it prints the Area, Circumference, and the Diameter of that Circle.”

Solution

class Circle // creating class called circle
{
public:

// constructor initializes radius with double supplied as argument
Circle( double rad )
{
setradius( rad ); // call set function to initialize radius
} // end Circle constructor

void setradius( double rad )
{
radius = rad;

if ( radius < 0 )
{
radius = 0;
}
}

double getradius()
{

return radius;

}

double diameter()
{

double r;

r = getradius();

return 2*r;

}

double circumference()
{

double c;

c = getradius();

return 2*3.14*c;

}

double area()
{

double a;

a = getradius();

return 3.14*a*a;

}

void displayMessage()
{
cout << "The Radius is: " << getradius() << "\nThe Diameter is: " << diameter() << "\nThe Circumference is: " << circumference() << "\nThe Area is: " << area() << endl;

}

private:

double radius;

};


// function main allow program to execution
int main()
{


Circle C(1.5); // Creating an object from the class and send the constructor 1.5 as the Radius value.



C.displayMessage();


return 0;

} // end function main

0 comments:

Post a Comment