Shape.h
namespace Graphics {
class Shape {
public:
virtual void Render(Point point) {};
};
}
Rect.h
namespace Graphics {
class Rect : public Shape {
public:
Rect(float x, float y);
Rect();
void setSize(float x, float y);
virtual void Render(Point point);
private:
float sizeX;
float sizeY;
};
}
struct ShapePointPair {
Shape shape;
Point location;
};
Used like this:
std::vector<Graphics::ShapePointPair> theShapes = theSurface.getList();
for(int i = 0; i < theShapes.size(); i++) {
theShapes[i].shape.Render(theShapes[i].location);
}
This code ends up calling Shape::Render
and not Rect::Render
I'm assuming this is because it is casting the Rect
to a Shape
, but I don't have any idea how to stop it doing this. I'm trying to let each shape control how it is rendered by overriding the Render
method.
Any ideas on how to achieve this?
Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword. Overriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name).
The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides.
The @Override annotation indicates that the child class method is over-writing its base class method. It extracts a warning from the compiler if the annotated method doesn't actually override anything. It can improve the readability of the source code.
Call super is a design pattern in which a particular class stipulates that in a derived subclass, the user is required to override a method and call back the overridden function itself at a particular point.
Here's your problem:
struct ShapePointPair {
Shape shape;
Point location;
};
You are storing a Shape
. You should be storing a Shape *
, or a shared_ptr<Shape>
or something. But not a Shape
; C++ is not Java.
When you assign a Rect
to the Shape
, only the Shape
part is being copied (this is object slicing).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With