Starting from:

$29.99

Lab 10: Inheritance and Virtual Functions

CS 2401 
Lab 10: Inheritance and Virtual Functions

The lab this week is to write some inherited classes that use 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, if
they are labeled as virtual in the parent.
I have provided the main, but 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
o M_PI * radius * radius (M_PI is defined in the library cmath.)
• Rectangle: length & width
o length * width
• Trapezoid: base1, base2, & height
o height * (base1 + base2) / 2.0
In the Shape class the cost function will return
• thickness * cost_per * area()
For this to work you will need to declare a virtual function for area in the Shape class, even
though it is implemented in the child.
When you first run this program, you will 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 sample output in which you create a box of at least five shapes.

More products