Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, is this method call static binding or dynamic binding?

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:

enter image description here

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?

like image 485
Hanfei Sun Avatar asked Jan 13 '16 11:01

Hanfei Sun


People also ask

Does C use static or dynamic binding?

C is a statically compiled language, it doesn't really have "dynamic binding".

Does C 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.

Is binding static or dynamic?

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.

What languages use dynamic binding?

Smalltalk, Objective-C, Modula-3, Python, and Ruby use dynamic method binding for all methods.


2 Answers

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.

like image 182
Jarod42 Avatar answered Sep 19 '22 17:09

Jarod42


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.

like image 40
Tanmay Dalvi Avatar answered Sep 21 '22 17:09

Tanmay Dalvi