In: Computer Science
Describe a scenario/design where a polymorphic behavior is utilized. In the lecture this week we studied an example in which we defined a GeometricObject as the base class and added features to this base class to define two specialized classes, namely the Circle and the Rectangle classes. Your design should have the design elements of the example we studied but it doesn’t have to be related to geometric shapes. Clearly list the functions in the base class you would declare as virtual, what is the expected behavior? And what happens if the functions are not made virtual? Do not code, describe your design and all features of a polymorphic design requirements.
Consider the example given in the problem as the base is the GeometricObject and the derived classes are Circle and Rectangle.
Therefore, the structure will may be as follows:
class GeometricObject{
};
class Circle: <access_specifier> GeometricObject
{
};
class Rectangle: <access_specifier> GeometricObject
{
};
class GeometricObject{
public:
virtual void Area()
{
}
virtual void Description()
{
}
};
class Circle: <access_specifier> GeometricObject
{
public:
Circle(){}
void Area()
{
}
void Description()
{
}
};
class Rectangle: <access_specifier> GeometricObject
{
public:
Rectangle(){}
void Area()
{
}
void Description()
{
}
};
int main()
{
//Pointer of Base class creating the object
//of Derived classes Circle and Rectangle.
GeometricObject *object = new Circle();
GeometricObject *object1 = new Rectangle();
//Functions of the class Circle is called.
object.Area();
object.Description();
//Functions of the class Rectangle is called.
object1.Area();
object1.Description();
}
Thus, for the dynamic binding or calling the functions of derived class with the pointer of the Base class, use the virtual keyword in the Base class functions.
Otherwise, compiler will always perform the static binding.