|
Initializing the Members of a Class Using a Constructor |
|
This example uses a class that contains a constructor
used to initialize the object. The class is called ShoeBox. When supplied with a length, a height,
and a width, the object should calculate and display the total area of all
sides and the volume. |
#ifndef SHOEBOX_H
#define SHOEBOX_H
class ShoeBox
{
public:
ShoeBox(double l, double h, double w);
double getLength() const;
double getHeight() const;
double getWidth() const;
void Properties();
double Area() const;
double Volume() const;
private:
double Length;
double Height;
double Width;
};
#endif
#include <iostream.h>
#include "box.h"
ShoeBox::ShoeBox(double l, double h, double w)
{
Length = l;
Height = h;
Width = w;
}
double ShoeBox::getLength() const
{
return Length;
}
double ShoeBox::getHeight() const
{
return Height;
}
double ShoeBox::getWidth() const
{
return Width;
}
double ShoeBox::Area() const
{
return 2 * ((Length * Height) + (Height + Width) + (Length * Width));
}
double ShoeBox::Volume() const
{
return Length * Height * Width;
}
void ShoeBox::Properties()
{
cout << "Properties of the shoe box";
cout << "\nLength = " << getLength();
cout << "\nHeight = " << getHeight();
cout << "\nWidth = " << getWidth();
cout << "\nArea = " << Area();
cout << "\nVolume = " << Volume() << "\n\n";
}
#include "box.h"
void main()
{
ShoeBox Size6(8.65, 4.25, 4.15);
Size6.Properties();
}
Here is a result of running the program
Properties of the shoe box
Length = 8.65
Height = 4.25
Width = 4.15
Area = 162.12
Volume = 152.564