Hi,
Pretty good effort for your code :+)
You already have all the stuff you need for polymorphism, just call the function - the compiler will do the right thing:
24 25 26 27 28
|
//Loop each index of array and perform calculation
for (int i = 0; i < 6; ++i)
{
cout << "Area is " << arr[i]->getArea() << "\n";
}
|
To print the name of each shape, put a virtual function in the Shape class - getName() (along with a string Name variable) and override it in all the derived classes.
Some extra things, maybe a little advanced:
Mark all of your get functions
const
, they don't change the state of the class, that is don't change any values of the member variables.
Parameters in your constructors should be
const
as well, the compiler can enforce the idea that you won't change the argument's value in the function.
When you override a virtual function, use the c++11
override
keyword, here is one example - you should do it for all of them in the header files:
45 46 47 48 49 50
|
class Circle : public TwoDimensionalShape {
public:
Circle(); //default constructor
Circle( double r); //regular constructor
double getArea() override; //get area function
};
|
The virtual functions in the Shape class could be pure virtual, forcing them to be overriden in the derived classes.
Probably shouldn't have protected member data, I know it's easy, but member data should be private. You already have member functions to retrieve their values.
You can use a member initialization list rather than assignment to set values in your constructor:
1 2 3 4 5 6 7
|
//Regular constructor--------------------
Triangle::Triangle(const double dim,
const double dim2)
: // colon introduces a member init list
d1(dim), // direct initialization, avoids intialization, copying
d2(dim2) // then assignment again
{}
|
Good Luck !!