Description
The lab this week is to implement the example that I have shown in Lecture5_4_Virtual_Fucntions, demonstrating derived classes and virtual functions. Because a child can be passed where a parent is expected we can use a parent pointer to hold a child object. In doing this no information is lost due to slicing.
Now, at first it seems that this pointer would only be able to call functions that were part of the parent, but because a virtual function allows a parent function to call a function implemented in the child we are able to call functions from the parent functions, and from the parent pointer, provided that they are labeled as virtual in the parent.
I have written the main for your project and you can copy it at ~jdolan/cs2401/labs/lab5 or from Blackboard. It will not compile until you have written the required classes.
You should write a Shape class with a default constructor, an input function (at first without the word virtual), a cost function, and private variables for thickness and cost_per_cubic_unit (you can shorten the name if you like). From this class you are to derive the classes Circle, Rectangle, and Trapezoid. Each of these will have a default constructor, an input function and a function that returns the area of the shape. The private variables and area formulas are:
• Circle: radius – formula = M_PI*radius*radius (M_PI is defined in the library cmath.)
• Rectangle: length & width – formula = length*width
• Trapezoid: base1, base2, & height- formula = height*(base1+base2)/2.0
In the Shape class the cost function will return
• thickness*cost_per*area()
In order for this to work you will need to declare a virtual function for the area in the Shape class, even though it is implemented in the child
When you first run this program you find that all the classes are calling your Shape input function, asking for thickness and cost_per instead of the appropriate measurement. You can fix this by putting the word virtual in front of the input function in the parent. Then you see the child function being called. (The child function can call the parent function using scope resolution, or you can set default values for the thickness and cost_per.)
You can implement all four classes with one .h file and one .cc file.
Submit these files along with a script in which you create a box of at least five shapes.