Sunday 24 May 2020

Chapter 13 // Exercise 18 - Principles & Practice Using C++

In this exercise I am using Visual Studio 2017 and the graphics files found here:
https://github.com/l-paz91/principles-practice/tree/master/Graphics%20Files

Chapter 13 // Exercise 18

Define a class Poly that represents a polygon but checks that its points really do make a polygon in its constructor. Hint: You'll have to supply the points to the constructor.

Github: https://github.com/l-paz91/principles-practice/tree/master/Chapter%2013/Exercise%2018


At first I thought he just meant check that the points are a Polygon and I was "the code already does that" however the problem comes in supplying points in the constructor. We don't know how many points will be supplied which means that the constructor needs to take in a initialiser_list<> which can be of any size. There's already a constructor of this type in the main base class Shape. As Poly derives from Shape we can use this constructor, however there was no definition so I quickly added it:
If you've ever initialised a vector like this:
vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9 };

Then you've used the initializer_list<> without realizing it. It's a great tool in the std library to allow you to initialise an object with an undetermined amount of items. Of course I'd recommend declaring the size wherever possible for the best performance.

The next thing to do is give open_polyline this constructor as you can only inherit from direct base classes. In this case the direct base class for Poly is Open_polyline whose base is Shape.

Once this is done, default constructors will need to be added to each class to remove any errors. 



No comments:

Post a Comment