C++ Define an abstract base class called BasicShape . The BasicShape class shoul
ID: 3695453 • Letter: C
Question
C++
Define an abstract base class called BasicShape. The BasicShape class should have the following members:
Protected Member Variable: area (a double used to hold the shape’s area).
Private Member Variable: name (a string to indicate the shape’s type)
Constructor and Public Member Functions:
BasicShape(double a, string n): A constructor that sets value of member area with a and member name with n.
calcArea(): This public function should be a pure virtual function.
print(): A pubic virtual function that prints the value of data member area
getName():A pubic function that returns the value of data member name
Define a class named Circle. It should be derived from the BasicShape class.
It should have the following members:
Private Member Variable: radius (a double used to hold the circle’s radius)
Constructor and Public Member Functions:
Circle(double a, string n, double r): constructor that should call the base class constructor to set value of member area with a and name with n. The constructor will also set value of member radius with r
calcArea(): Overridden function that calculates the area of the circle (area = 3.14159 * radius * radius) and stores the result in the inherited member area.
print(): Overridden function that will print the radius, inherited member area and inherited member name. This function should use the base class’s print function to print the area.
After you have created these classes, create a test program
Write a function named poly whose only parameter is a BasicShape pointer.
Function poly should use the BasicShape pointer to invoke calcArea function and print function.
In main(): define a Circle object with radius 10, name Round and area initialized to 0.
From main(), call the function poly such that it will polymorphically invoke calcArea function and print function of the Circle object
Explanation / Answer
#include <iostream>
#include <iomanip> // std::setprecision
using namespace std;
class BasicShape //Abstract base class
{
protected:
double area;
private:
string name;
public:
virtual void calArea()=0; //Pure Virtual Function
BasicShape(double a, string n):area(a),name(n){}
virtual void print();
string getName()
{
return name;
}
};
class Circle : public BasicShape {
private:
double radius;
public:
Circle(double a, string n, double r): BasicShape(a,n),radius(r) {}
virtual void calArea(){area = 3.14159 * radius * radius;
}
virtual void print()
{
cout<<"Radius::"<<radius;
cout<<"Area::"<<BasicShape::area;
cout<<"Name::"<<getName();
}
};
void poly()
{
BasicShape *pointer;
pointer->calArea();
pointer->print();
}
int main()
{
Circle c(10,"Round",0);
poly();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.