Question: Part 2 - Coding: Objects, Inheritance and Polymorphism Write code for a class called Shape which has a constructor which takes a string representing the
Part 2 - Coding: Objects, Inheritance and Polymorphism
Write code for a class called Shape which has a constructor which takes a string representing the name of the shape and has three methods called
- get_area(); which returns a double value 0.0
- get_perimeter(); which has no implementation in Shape but is provided by all classes which inherit from Shape,
- get_name(); which returns the name given to the shape when it was created
You may define additional methods as needed.
Now write the following classes that inherit from shape.
- Circle which takes a diameter and a name in its constructor. The get_area() method will return the area of the circle which is pi*diameter where pi is 3.1415926. The get_perimeter() method will return pi*diameter.
- Rectangle which takes a length and height in its constructor. The get_area() and get_perimeter() method will need to return the appropriate values for a rectangle. All rectangles have the name "Rectangle".
- Triangle which takes the following parameters: an integer representing the length of the triangle base, two integers representing the length of the other two sides sides of the triangle and a double representing the height of the triangle. The constructor should check to see that the side lengths are valid (ie the sum of any two sides must be greater than the third side) and prints an error message otherwise. The get_area() method returns 0.5*base_length*height (or 0.0 if the triangle is invalid). The get_perimeter() method will return the sum of the length of the sides (or 0.0 if the triangle is invalid). The Triangle's name should be one of "Equilateral", "Isosceles" or "Scalene" based on the lengths of its sides.
Now write a driver program called ShapeDriver.cpp that contains a main method that instantiates a range of shapes (most valid but some invalid) places them in a vector of Shape and then runs the get_area(), get_name() and get_perimeter() functions on each printing the results to the screen.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
