create a class called Box which has private data members: length and width, both
ID: 3679301 • Letter: C
Question
create a class called Box which has private data members:
length and width, both float
area, found from length and width
name which is a dynamic string
constructor
1)create a contructor with default parameters of 1 for length and width.
2)the constructor should calculate ther area member frm length and width.
3)add a static member called total_area.In the constructor,add the area of the box created toi total_area variable.
4)add a comment with cout<<creating a box using the name data member.
member function
create a member function called perimeter() which finds the perimeter of a box,and returns this value.
p=2(L+W) WHERE p=perimeter, L=length , W=width
Non-member function
create a non member friend function called fits.this function takes 2 boxes as arguments(pass b reference) and returns true if the
first box would fit inside the second box , else return false.
one way to tell if box A fits in box B is if the length of A< length of B and width of A<width of NB
destructor
create destructor the iutputs a message deleting a box usig its name member
in main();
instaniate 3 boxes with the constructor using code:
Box b1("first",2,3);
Box b1("second",5);
Box b1("third");
use the perimeter function for one of the boxes
use the fits function for anty two of the boxes
casll the function froom main() something like
if(fits(b1.b2))
cout<<"box fits ";
else
cout<<"box doesn't fit ";
when program finishs print out total area of the 3 boxes from this variable.
Explanation / Answer
Code:
#include <iostream>
#include <cstdlib>
#include<string>
using namespace std;
class Box
{
private:
float length,width,area;//declaration of data members
string name;
public:
static float total_area; //declaring static variable, remember we still need to define static variable otherwise it throws an error
Box()
{
}
Box(string n,float l=1, float w=1)//initialization of data members
{
length = l;
width = w;
area= l*w;
total_area+=area;
name=n;
//cout<<"creating a box "<<name<<endl;
}
float perimeter()//function for calculating perimeter
{
return 2*(length+width);
}
friend bool fits( Box b1,Box b2 )//friend function ( it will access the private data members of the class)
{
if(b1.length < b2.length && b1.width <b2.width)
return true;
else
return false;
}
};
float Box::total_area;
int main ()
{
Box b1("first",2,3); //constructor call
Box b2("second",5);
Box b3("third");
cout<<"perimeter of first box:"<<b3.perimeter()<<endl;
if(fits(b3,b1))
{
cout<<"box fits"<<endl;
}
else
{
cout<<"box doesn't fits";
}
cout<<"total area is: " << Box::total_area;
}
Sample Input and Output:
perimeter of first box:4
box fits
total area is: 12
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.