Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Binding in C++

I need some clarification on dynamic binding in C++ .I'm confused about the following:

  1. In C you can have an array of function pointers & assign different functions of the same signature & call them based on the index; is this Dynamic binding?

  2. In C++ you can have an array of base class pointers but you can call different functions of the derived class, by assigning the derived class objects addresses to a base-class array of pointers & by using virtual functions, Is this Dynamic Binding?

  3. Which term is correct - Dynamic binding or Link-Time Binding?

like image 836
Arjun Avatar asked Apr 10 '09 13:04

Arjun


3 Answers

Answers

  1. No. This is much closer to dynamic dispatch than dynamic binding. Dynamic binding refers to the way in which a named method is bound at runtime. There is no name here.
  2. Yes. If the methods are virtual then this is the definition of dynamic binding. The name is known at compile time but the method called cannot be determined without knowing the runtime object type
  3. I'm not sure what you mean here. Dynamic binding is the more idiomatic term.
like image 178
JaredPar Avatar answered Sep 24 '22 20:09

JaredPar


I'd call both of these uses of dynamic binding. In C++, the language is giving you the mechanism, so that you don't have to roll your own as you do in C.

(I once worked with an app in which every major object was passed around accompanied by a struct whose fields were function pointers. The struct's purpose was to allow the app to implement run-time dynamic binding -- that is, to change the assigned functions for the object at runtime, depending on the object's state. This "feature" was never taken advantage of, so far as I know.)

like image 23
Dan Breslau Avatar answered Sep 21 '22 20:09

Dan Breslau


Dynamic binding is binding interface to its implementation at runtime - any situation when the program automatically decides which code to call as interface implementation. So generally speaking both 1) and 2) are dynamic binding, but the term is usually only used for 2).

Link-time binding (aka early binding) is the opposite of dynamic binding (aka late binding). In link-time binding the compiler/linker knows exactly what code to call and gererates a direct call of that code. In dynamic binding the compiler/linker doesn't know that - exact implementation is determined at runtime.

like image 42
sharptooth Avatar answered Sep 20 '22 20:09

sharptooth