Write a class called Box that has three double fields called height, width and l
ID: 3860535 • Letter: W
Question
Write a class called Box that has three double fields called height, width and length. The class should have set methods for each field. It should have a three-parameter constructor that takes three doubles and passes them to the set methods to initialize the fields of the Box. It should have a default constructor that uses the set methods to initialize each field to 1. It should have a method that calculates and returns the volume of the Box and a method that calculates and returns the surface area of the Box.
The class declaration (interface) and the function definitions (implementation) must be in separate files - the interface or "header" file has a .hpp extension and the implementation has a .cpp extension. As usual, all data members should be private. The Box class might be used as follows:
Your functions should have the following names:
setHeight
setWidth
setLength
calcVolume
calcSurfaceArea
Explanation / Answer
Box.hpp
#ifndef BOX_HPP
#define BOX_HPP
using namespace std;
class Box{
double height, width,length;
public:
Box();
Box(double,double,double);
void setHeight(double);
void setWidth(double);
void setLength(double);
double getVolume();
double getSurfaceArea();
};
#endif
Box.cpp
#include<iostream>
#include "Box.hpp"
using namespace std;
void Box::setLength( double len )
{
length = len;
}
void Box::setWidth( double wid )
{
width= wid;
}
void Box::setHeight( double hei )
{
height = hei;
}
Box::Box()
{
setLength(1);
setWidth(1);
setHeight(1);
}
Box::Box(double len,double wid,double hei)
{
setLength(len);
setWidth(wid);
setHeight(hei);
}
double Box::getVolume()
{
return length*height*width;
}
double Box:: getSurfaceArea()
{
return (2*length*width)+(2*length*height)+(2*width*height);
}
main.cpp
#include<iostream>
#include "Box.hpp"
using namespace std;
int main()
{
Box B;
cout<<"Volume: "<<B.getVolume();
cout<<" Surface area: "<<B.getSurfaceArea();
Box B1(3,4,1);
cout<<" Volume: "<<B1.getVolume();
cout<<" Surface area: "<<B1.getSurfaceArea();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.