views:

1341

answers:

5

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?

+4  A: 

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.
JaredPar
Yes, But are they used to accomplish the same goal more or less ??
Arjun
@Arjun, yes the accomplish the same idea, the method is slightly different though
JaredPar
A: 

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.

sharptooth
A: 

Have you tried writing a code In C language? Which compiler you used for this? You can't have two functions with same name in C language.

Haranadh
Oh...I ment two function of the same type...I did'nt know that signature also ment the function's name...thanks
Arjun
+1  A: 

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.)

Dan Breslau
+1  A: 

You're confusing the concept of dynamic binding with the implementation. Dynamic binding, i.e. choosing which method to call based on the receiving object's type, may be implemented using some form of dynamic dispatch, i.e. your (1), but we generally define the name to only refer to situation (2).

Andy