Simple Inheritance

Exercise 1: Colon Syntax
The colon syntax can improve the performance of constructors. To test this, make sure that you print some text in the point’s constructors, destructor and also the assignment operator. Now, execute the following code in the test program and count the number of point constructor, destructor and assignment calls:
Line l;
Now, change the constructors in the Line class to use the colon syntax to set the start- and end-point data members and run the test program again. Is the number of point constructor, destructor and assignment calls less than before? Apply the colon syntax also for the Point class constructors and if applicable also for the Circle class.

 

Exercise 2: Creating Shape Base Class
It can be useful to create a hierarchy of related classes using base- and derived classes.
•Classes are related (same family)
•Common data and functionality can be put in a base class.
•You can work with derived classes as if it is the base class.
In this exercise we are going to transform the Point and Line class into a Shape hierarchy as shown in Figure 1.

First create a Shape base class.
•Add a source- and header file for a Shape class.
•Add a data member for an id number of type int.
•Add a default constructor that initializes the id using a random number. You can usethe rand() function from the “stdlib.h” header file.
•Add a copy constructor that copies the id member.
•Add an assignment operator that copies the id member.
•Add a ToString() function that returns the id as string e.g. “ID: 123”.
•Add an ID() function the retrieve the id of the shape.
Next the Point and Line classes (and the Circle class if applicable) must derive from Shape.
•Add the Shape class in the inheritance list of the Point, Line and optionallythe Circle class.
•The constructors of the Point, Line and optionally the Circle class should call theappropriate constructor in the Shapebase class.
•The assignment operator should call the assignment operator of the Shape baseclass. Otherwise the shape data will not be copied.
•Finally add code to the main program to test inheritance:

Leave a Reply

Your email address will not be published. Required fields are marked *