Practice #2

Download code here

Create a class to represent Rectangles. A rectangle has length and width data members. Add member functions to allow access to Rectangle data members

		class Rectangle
		{
		public:
			void SetLenght (float l)
			{
				length = l;
			}

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

			float GetLenght ()
			{
				return length;
			}

			float GetWidth ()
			{
				return width;
			}

		private:
			float length;
			float width;
		};
		

Write a simple main function to test your code

		void main ()
		{
			Rectangle r1, r2;
			r1.SetLength (10);
			r1.SetWidth (5);
			
			r2.SetLength (10);
			r2.SetWidth (5);
			
			// increase r1 length by 1
			r1.SetLength (r1.GetLength () + 1);
			// ....
			// ....
		}
		

Write a function named Area that returns the Rectangle Area.
Area = length * width

		float Area ()
		{
			return length * width;
		}
		

Write a function named Equal that takes a Rectangle object, return true of both rectangles are equal, false otherwise

		bool Equal (const Rectangle& r)
		{
			return length == r.length && width == r.width;
		}
		

In your main function, test your code

		void main ()
		{
			// ...

			cout<<"r1 Area = "<< r1.Area ()<< endl;
			cout<<"r2 Area = "<< r2.Area ()<< endl;
		
			if (r1.Equal (r2))
				cout<<"Both rectangles are Equal\n";
			else
				cout<<"Not Equal\n";

			if (r2.Equal (r1))
				cout<<"Both rectangles are Equal\n";
			else
				cout<<"Not Equal\n";
			// ...
		}
		

Write a constructor function to initialize data member when new Rectangle objects are created
constructor functions have the same name as class and are automatically called when objects are created

		Rectangle (float l, float w) // constructor : used to initialize data members
		{
			length = l;
			width = w;
		}
		

In your main function, create new Rectangle objects and pass length and width to constructor

		void main ()
		{
			Rectangle r1 (12, 6), r2 (10, 7);	// constructor is automatically called
			// ...
		}