If I create a pointer out of my Shape base class, how would I got about making it behave like the circle (derived) class? Here are my class definitions:
//CShape.h class definition
//Shape class definition
#ifndef CSHAPE_H
#define CSHAPE_H
class CShape
{
protected:
float area;
virtual void calcArea();
public:
float getArea()
{
return area;
}
};
class CCircle : public CShape
{
protected:
int centerX;
int centerY;
float radius;
void calcArea()
{
area = float(M_PI * (radius * radius));
}
public:
CCircle(int pCenterX, int pCenterY, float pRadius)
{
centerX = pCenterX;
centerY = pCenterY;
radius = pRadius;
}
float getRadius()
{
return radius;
}
};
In my project file where I’m calling these objects, I have the following code:
CShape *basePtr = new CCircle(1, 2, 3.3);
basePtr->getRadius();
It seems to me like this should work, however I’m told CShape has no member “getRadius().”
EDIT
Based on the response below I tried to dynamic_cast the basePtr object to CCircle like so:
CCircle *circle = new CCircle(1, 2, 3.3);
basePtr = dynamic_cast<CCircle *>(circle);
This failed too, however. I’ve never done a dynamic_cast and am unfamiliar with most of the syntax in C++, so any help is greatly appreciated.
To get to
getRadiusfunction you must declare it of typeCCircle:Otherwise, if you want to declare
basePtrasCShape, use dynamic binding withdynamic_castor use c-style cast directly, as @Janisz pointed out.