Here is the class definition:
class Shape { public:
virtual void draw() = 0; ...
};
class Circle : public Shape {
public:
void draw() { ... }
... };
class Rectangle : public Shape { public:
void draw() { ... } ...
};
class Square : public Rectangle {
public:
void draw() { ... }
... };
And here is the client code:
Square* sq = new Square;
Rectangle* rect = new Rectangle;
Shape* ptr_shape;
ptr_shape = sq;
ptr_shape->draw();
rect->draw();
A book that I was reading said the last statement is static binding:
However, the statement still looks dynamic binding to me because rect->draw
should be called by the pointer in the "vtable" of rect
in run-time.
Does anyone have ideas about whether the rect->draw
is static binding or dynamic binding?
C is a statically compiled language, it doesn't really have "dynamic binding".
Dynamic binding is also referred to as late binding. In Objective-C, all methods are resolved dynamically at runtime. The exact code executed is determined by both the method name (the selector) and the receiving object. Dynamic binding enables polymorphism.
The static binding uses Type information for binding while Dynamic binding uses Objects to resolve to bind. Overloaded methods are resolved (deciding which method to be called when there are multiple methods with the same name) using static binding while overridden methods use dynamic binding, i.e, at run time.
Smalltalk, Objective-C, Modula-3, Python, and Ruby use dynamic method binding for all methods.
Rect::draw()
is not final
and rect
is a pointer, so it uses dynamic binding.
But the compiler may use de-virtualization as optimization if all variables are in local scope and all types are known.
You're overall understanding of the vtable is correct.
I think what the book is trying to say is that the compiler might, and generally will, optimise the rect->draw to be called without going to the vtable.
In this case, the compiler can see that the rect is pointing to a Rectangle object.
In most production code, this will rarely be the case.
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