Practice #4

Download code here

[inside Rectangle.h]

		#ifndef RECTANGLE_H
		#define RECTANGLE_H

		class Rectangle
		{
		public:
			Rectangle (float = 0, float = 0);

			float GetLength () const;
			float GetWidth () const;

			void SetLength (float);
			void SetWidth (float);

			float Area () const;
			float Perimeter () const;

		private:
			float length, width;
		};

		#endif
		

[inside Rectangle.cpp]

		#include "Rectangle.h"

		Rectangle::Rectangle (float l, float w)
		: length (l), width (w)
		{
		}

		float Rectangle::GetLength () const
		{
			return length;
		}

		float Rectangle::GetWidth () const
		{
			return width;
		}

		void Rectangle::SetLength (float l)
		{
			length = l;
		}

		void Rectangle::SetWidth (float w)
		{
			width = w;
		}

		float Rectangle::Area () const
		{
			return length * width;
		}

		float Rectangle::Perimeter () const
		{
			return 2 * (length + width);
		}
		

[inside Box.h]

including "Rectangle.h" is necessary because Box inherits Rectangle

		#ifndef BOX_H
		#define BOX_H

		
		#include "Rectangle.h"

		class Box : public Rectangle
		{
		public:
			Box (float = 0, float = 0, float = 0);

			float GetHeight () const;
			void SetHeight (float);

			float Area () const;
			float Volume () const;

		private:
			float height;
		};

		#endif
		

[inside Box.cpp]

		#include "Box.h"

		Box::Box (float l, float w, float h)
			: Rectangle (l , w), height (h)
		{
		}

		float Box::GetHeight () const
		{
			return height;
		}

		void Box::SetHeight (float h)
		{
			height = h;
		}

		float Box::Area () const
		{
			return 2 * ((GetLength () * height) +
						(GetLength () * GetWidth ()) +
						(GetWidth () * height));
		}

		float Box::Volume () const
		{
			return Rectangle::Area () * height;
		}
		

[inside main.cpp]

		#include 
		using namespace std;

		#include "Rectangle.h"
		#include "Box.h"

		void main ()
		{
			Rectangle R (5, 10);
			Box B (3, 4, 5);

			// B inherits all data and functions in Rectangle, e.g.
			cout<< B.GetLength ()<< endl;			// 3
			cout<< B.GetWidth ()<< endl;			// 4

			cout<< R.Area ()<< endl;				// 50

			// B has two copies of Area () function
			cout<< B.Area ()<< endl;				// 94
			cout<< B.Rectangle::Area ()<< endl;	// 12
		}