9

This link helped me understand the difference between static binding and dynamic binding? but I am in a confusion that

what is the difference between static binding and compile time polymorphism or no difference is there.

This also creates a doubt about dynamic binding and runtime polymorphism?

Community
  • 1
  • 1
nitesh.kodle123
  • 1,041
  • 4
  • 11
  • 23
  • 4
    Compile-time polymorphism is a fancy (and arguably somewhat misleading) name for static binding. It's not overly popular either - most prefer calling it "overloading". – Sergey Kalinichenko Feb 27 '14 at 11:11
  • 1
    This could be interesting question if asked with some code examples and references. – LihO Feb 27 '14 at 11:18
  • 1
    Related: [Compile time vs run time polymorphism in C++ advantages/disadvantages](http://stackoverflow.com/q/16875989) – jww Nov 30 '15 at 20:57

5 Answers5

8

In short

Static vs dynamic binding is about when the exact code to run (i.e. the function's address) is known: at compile-, link- (both "static"), load-, or run-time (both "dynamic").

Polymorphism is firstly about how the exact code to run is known: to qualify as polymorphism, it's necessarily inferred from the type of data being processed. When the "dynamic type" of data is not known until run-time (often because the type is determined by run-time data inputs) dynamic binding must be used, and that requires dynamic polymorphism (aka runtime polymorphism; C++ offers the virtual dispatch mechanism in this category). There are other situations when virtual dispatch is useful even though the types of data being processed are available at compile time - particularly for minimising/eliminating (re)compile times after code changes, and for tuning code "bloat". Anyway, compile-time aka static polymorphism uses what's known about the types at compile time to bind at compile- or link- time (i.e. "statically").

Examples

struct Base { virtual void f(); void g(); };
struct Derived : Base { void f(); void g(); };

Derived d;
d.f();    // if definition's in a shared library, needs dynamic binding
          // otherwise (same translation unit, linked object, static lib)
          // compiler should optimise to static binding
          // (though functionally either would work)

Base* p = factory(data);
p->f();   // dynamic binding - if p points to a Base, use Base::f()
          //                 - if p pointer to a Derived, use Derived::f()

void some_func(const char*);  // note: no polymorphism / overloads

some_func("hello world\n");
       // if some_func is defined in...
       //  - shared / dynamic link library, binds dynamically
       //  - otherwise, static binding

std::cout << "hello world\n";  // static binding
                               // compile-time polymorphism from (operator) overloading

Discussion

binding normally refers to the time at which the program resolves a function call to a specific function implementation's machine code:

  • static means this happens during compilation

  • dynamic means this happens when the executable program is launched/running

"binding" - and "currying" - are also used to describe the stipulation of arguments to functors (search for "binding" in Stroustrup's C++11 FAQ)

The only situations in which C++ programs bind function calls dynamically are:

  • when a dynamic library is used, in which case the binding may be done by the Operating Systems loader before main() is called, or explicitly in code using dlsym (or similar OS-specific function), which returns a function pointer to use to call a function found in a dynamic library (.so, .dll, ...).

  • in virtual dispatch, when a virtual member function is found at run-time, typically by following a pointer from the data-object to a virtual dispatch table where the function pointer's recorded

  • when function pointers are used explicitly by the programmer

In other situations, binding is static: the compiler itself writes a jmp or call to a specific memory address/offset (whether absolute or relative to the Program Counter doesn't matter) into the object or executable it creates, and that is not modified during program loading or execution.

The static / dynamic binding classification only has a little overlap with polymorphism:

  • virtual dispatch normally uses dynamic binding (but can sometimes be optimised as per Examples above) and

  • all other forms of polymorphism in C++ (namely overloading, templates, inlined macro expansions) use static binding, but

  • so does most non-polymorphic code: any "normal" non-virtual call to a function that's not in a shared/dynamic library is resolved at compile time too.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • These are very useful pointers for me.Can you please share some links that I can understand this concept in a better way. – nitesh.kodle123 Feb 27 '14 at 11:54
  • 1
    @nitesh.kodle123: Well, I think some background on polymorphism should help - I'll shamelessly plug [my own writeup on StackOverflow](http://stackoverflow.com/questions/5854581/polymorphism-in-c/5854862#5854862). For binding, I'll have to dig around for a really good link - not sure yet. – Tony Delroy Feb 27 '14 at 12:42
4

Polymorphism refers to the ability of an object to behave differently to the same message.

Polymorphism is of two types. static or dynamic. In dynamic polymorphism the response to message is decided on run-time while in static polymorphism it is decided on compile-time.

The assignment of data types in dynamic polymorphism is known as late or dynamic binding. In dynamic binding method call occur based on the object (instance) type at Run time. Eg: method overriding

If the assignment of data types is in compile time it is known as early or static binding. In static binding method call occur based on the reference type at compile time. Eg: method overloading

Method Overloading - This means creating a new method with the same name and different signature. It uses early binding.

Method Overriding - This is the process of giving a new definition for an existing method in its child class. All object created at run time on the heap therefore actual binding is done at the runtime only.

user3217843
  • 424
  • 1
  • 3
  • 17
  • This is a very "computer science" description, a little different from the day-to-day C++ programmer's perspective. Most is right though, so +1. Some's ambiguous: e.g. "ability... to behave differently to the same message" - any function with state can do that across calls, but polymorphism is specifically about dispatching to potentially different *code* based on the type of the object, and given the same semantic usage of the object. And method overriding can be used with objects not on the heap: `void print(Base*); Derived d; print(d);` - just hard to move objects around that way. – Tony Delroy Feb 27 '14 at 12:29
2

Important difference is when error is shown if occurred. If you have static binding, it is possible to catch error at compilation time. Runtime error is harder to find.

Pingwin Tux
  • 124
  • 9
  • 1
    +1 Good point! For run-time polymorphism (virtual dispatch) it's rare to have errors with the binding per se, but for dynamic link libraries (shared objects) it can easily happen. – Tony Delroy Feb 27 '14 at 12:20
1

The difference is that first is the technique (binding) and second is the feature (polymorphism) that can be used basing on this technique.

Polymorphism means writing general code to work with different objects without knowing their exact types.

Static binding is a language property that allows the compiler to resolve the type called at compile time. But there can be static binding without polymorphism.

Dynamic binding is a language property which allows to decide about the type at run time. But there can be dynamic binding without polymorphism. If dynamic binding is used for writing general code which works with objects of several classes in hierarchy then it will be dynamic polymorphism.

Spock77
  • 3,256
  • 2
  • 30
  • 39
  • Thanks for suggestion.But can you please elaborate how static binding came be achieved without polymorphism. – nitesh.kodle123 Feb 27 '14 at 11:43
  • `SomeClass obj; obj.func();` static binding of SomeClass::func() function to definite address in memory at compile time. Binding is just conjunction of the name with machine address where the function or the variable are hold. – Spock77 Feb 27 '14 at 13:06
1

Compile time polymorphism is quite vague and contradictory. Polymorphism is used to call a specific method based upon the object type at runtime. It is intimately linked to late binding aka dynamic binding. You achieve that by using the virtual keyword:

class Base
{
    virtual void do() // Note the virtual
    {
        cout << "Base" << endl;
    }
};

class Derived : public Base
{
    virtual void do()
    {
        cout << "Derived" << endl;
    }
};

void use(Base& b)
{
    b.do(); // There you have late binding with 'virtual'
            // If you remove 'virtual', you have early binding,
            // Base::do() will be called everytime 
}

Base b;
Derived d;

use(b); // print Base
use(d); // print Derived, but print Base if you do not use virtual in Base.

Function overloading is just syntactic sugar, not related to polymorphism. You can use it to write:

 void use(int);
 void use(MyClass&);
 void use(const std::string&);

instead of:

 void useInteger(int);
 void useMyClass(MyClass&);
 void useString(const std::string&);

As you can use this with methods, you can believe it is related to polymorphism. Beware that it does not mix well with polymorphism !

Concerning static polymorphism, the term is sometime used to describe a pattern used with templates that mimicks polymorphism at compile time : see CRTP or Curriously Reccuring Template Pattern

neuro
  • 14,948
  • 3
  • 36
  • 59
  • If you premised what you've said with say *"In Computing Science 'polymorphism' encompasses both compile time (overloading, templates, macros) and run-time (virtual dispatch) mechanism, but the C++ Standard only uses the term 'polymorphism' to refer to virtual dispatch, and I'll do the same"* then it'd be less potentially confusing for readers. [further details](http://stackoverflow.com/questions/5854581/polymorphism-in-c/5854862#5854862). *"static polymorphism... sometime used to describe...CRTP"* is still misleading: CRTP is but one application of one type of static polymorphism. – Tony Delroy Sep 09 '15 at 02:11