Exercises in this lecture  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'  Go to the slide, where this exercise belongs -- Keyboard shortcut: 'u'  

Exercise 4.1
Methods in class Point and class Rectangle


In this exercise we will add methods to class Point and Rectangle from the enclosing slide.

First, however, we notice that a rectangle contains its two points. In a similar Java or C# program (programmed with classes) the rectangle would have references (in the meaning of C++ pointers) to two points.

Add a couple of methods that access the x and y coordinates of a point. This is very easy. Do you miss C#-like properties in C++?

Next, write two methods that access the two corner points of a rectangle. Do you want to return copies of the points? Pointers to the points? Or references to the points? Please play with each of these possiblities, and discuss pros and cons.

Add an area method to Rectangle. This method will most likely need to access to the x and y coordinates of the corner points of the rectangle.

Add move methods to both class Point and Rectangle. The methods should implement relative displacement of points and rectangles.

In Rectangle::move, are you able to establish (C++) references to its two corner points, such that moving the two points also will also move the rectangle?

If you get too frustrated by dealing with Point& you may consider a version that works on Point*...

Finally, supply output functions for Point and Rectangle objects, by overloading operator<< for these two classes.


Solution