Saturday, 27 January 2018

c++ - What should the TwoDimensionalShape Class contain?

Answer


Answer




I am trying to do an exercise with polymorphism in C++ to calculate the area and volume of the figures int the following hierarchy



                                       Shape
TwoDimensionalShape ThreeDimensional


Circle Square Triangle Sphere Cube


I declared a virtual function getArea and getVolume in the Shape class, and for example in the Circle class the function is:



double Circle::getArea() const
{
return 3.14*radius*radius;
}



where radius is private in the circle class.



But I am stuck a little on what should I include in the TwoDimensionalShape class and if I should declare a variable area inside it.


Answer



You don't need a data member inside intermediate level classes. They are just for hierarchy abstraction, in order to say Circle is a TwoDimensionalShape. You may later have some function taking reference to TwoDimensionalShape and where you can pass Circle or Triangle, but not any other non-TwoDimensionalShape.



As a data-member, you can have some flag within Shape itself. The data member would specify the type of current object. You can have enum for the same. This will be used for static-asserts and well as runtime checks. This may also help in some ways without need of virtual functions.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...