Re-write the derived classes from given code to override a pure virtual function in the base class to compute the area of the shapes. Re-write the application from before to create and store input shapes as base class pointers. In addition, modify the application to allow the user to create and store any number of shapes (use an STL class to store the base class pointers, i.e. vector<Shape *> shapes). After the user has finished creating shapes, compute and print the area for all the shapes in a single loop using only the base class pointers with dynamic binding.
______________________________________________________________________________________
VirtualPrint.C (program demonstrating how you can use dynamic binding to output parent and child information using base class pointers)
#include <iostream>
using namespace std;
// Parent class
class Parent
{
protected:
float val;
public:
// Overloaded output stream operator
friend ostream &operator<<( ostream &, Parent & );
// Pure virtual method
virtual ostream &Print( ostream & ) = 0;
// Access methods
void setVal( float f ) { val = f; }
int getVal() { return val; }
};
ostream &operator<<( ostream &strm, Parent &p )
{
strm << "Parent information: " << endl;
strm << " val: " << p.val << endl;
// Virtual print
return p.Print( strm );
}
// Child class
class Child : public Parent
{
protected:
int ival;
public:
// Virtual method
virtual ostream &Print( ostream & );
// Access methods
void setIval( int i ) { ival = i; }
int getIval() { return ival; }
};
ostream &Child::Print( ostream &strm )
{
strm << "Child information" << endl;
strm << " ival: " << ival << endl;
return strm;
}
main()
{
Child *c = new Child;
c->setIval( 44 );
Parent *p = c;
p->setVal( 4.5 );
cout << *p;
}
12 years ago
Purchase the answer to view it
- triangle_rectangle_circle_area_virtual_cpp_lab_9_answer.zip