nitesh.kodle123
nitesh.kodle123

Reputation: 1033

What is the difference between compile time polymorphism and static binding?

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?

Upvotes: 9

Views: 17237

Answers (5)

neuro
neuro

Reputation: 15180

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

Upvotes: 1

Tony Delroy
Tony Delroy

Reputation: 106096

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.

Upvotes: 8

Spock77
Spock77

Reputation: 3325

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.

Upvotes: 1

Pingwin Tux
Pingwin Tux

Reputation: 134

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.

Upvotes: 2

user3217843
user3217843

Reputation: 424

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.

Upvotes: 4

Related Questions