28

How does early and late binding look like in C++? Can you give example?

I read that function overloading is early binding and virtual functions is late binding. I read that "early (or static) binding refers to compile time binding and late (or dynamic) binding refers to runtime binding".

6
  • 1
    "[...] early (or static) binding refers to compile time binding and late (or dynamic) binding refers to runtime binding"..... Yes, that is all. What else do you want to know? What is your question/confusion/doubt?
    – Nawaz
    Aug 3, 2013 at 17:13
  • Can't believe this wasn't asked before.
    – Shoe
    Aug 3, 2013 at 17:15
  • 3
    Very old topic to be writing fresh examples for. Have a look at this link
    – loxxy
    Aug 3, 2013 at 17:16
  • Related (near dupe): stackoverflow.com/q/13023028/179910 Aug 3, 2013 at 17:20
  • @Nawaz Take a look at this example (openpaste.org/A9E72F27). I can see from this code that print() of class B will be executed. And if I can see it from the code then it is known at compile time, right? So it should be static binding. But virtual functions are dynamic binding!
    – Slazer
    Aug 3, 2013 at 17:55

3 Answers 3

27

You read right. The basic example can be given with:

using FuncType = int(*)(int,int); // pointer to a function
                                  // taking 2 ints and returning one.

int add(int a, int b) { return a + b; }
int substract(int a, int b) { return a - b; }

Static binding is when binding is known at compile time:

int main() {
    std::cout << add(4, 5) << "\n";
}

leaves no room for a dynamic change of the operation, and thus is statically bound.

int main() {
    char op = 0;
    std::cin >> op;

    FuncType const function = op == '+' ? &add : &substract;

    std::cout << function(4, 5) << "\n";
}

whereas here, depending on the input, one gets either 9 or -1. This is dynamically bound.

Furthermore, in object oriented languages, virtual functions can be used to dynamically bind something. A more verbose example could thus be:

struct Function {
    virtual ~Function() {}
    virtual int doit(int, int) const = 0;
};
struct Add: Function {
    virtual int doit(int a, int b) const override { return a + b; } 
};
struct Substract: Function {
    virtual int doit(int a, int b) const override { return a - b; } 
};

int main() {
    char op = 0;
    std::cin >> op;

    std::unique_ptr<Function> func =
        op == '+' ? std::unique_ptr<Function>{new Add{}}
                  : std::unique_ptr<Function>{new Substract{}};

    std::cout << func->doit(4, 5) << "\n";
}

which is semantically equivalent to the previous example... but introduces late binding by virtual function which is common in object-oriented programming.

6
  • 1
    Perhaps its also worth mentioning fixed address offsets vs vtable lookups.
    – Nikos C.
    Aug 3, 2013 at 17:18
  • 3
    @NikosC.: I was adding virtual methods already; I don't quite feel like adding vtables/v-ptr in response to what looks to be a beginner's question. It might be a little too in-depth. Aug 3, 2013 at 17:22
  • I am sorry but I dont understand the line "using FuncType = int(*)(int,int)"
    – Slazer
    Aug 3, 2013 at 17:29
  • @Slazer: That is C++11 syntax which means same as typedef int (*FuncType)(int,int) which in turn means FuncType is a pointer type to a function which takes two int parameters and returns int.
    – Nawaz
    Aug 3, 2013 at 17:35
  • @Slazer: adding to Nawaz' answer, in C++ you can manipulate pointers to functions (after, they too reside in memory). A pointer to function need be typed by the parameters and result type of the functions it may carry, otherwise you would not know what parameters to pass or what result to expect. This is just C++11 syntax to declare such a pointer to function; I find it somewhat clearer than C++03 syntax in which the newly declared entity is mixed up within the type :x Aug 3, 2013 at 17:37
5

These are true of all object-oriented languages, not just C++.

Static, compile time binding is easy. There's no polymorphism involved. You know the type of the object when you write and compile and run the code. Sometimes a dog is just a dog.

Dynamic, runtime binding is where polymorphism comes from.

If you have a reference that's of parent type at compile type, you can assign a child type to it at runtime. The behavior of the reference will magically change to the appropriate type at runtime. A virtual table lookup will be done to let the runtime figure out what the dynamic type is.

3
  • Note: C++ is more than just an object-oriented language, and thus has more ways of using late-binding. Function pointers, for example, are one way (and used underneath the tables to implement virtual functions actually). Aug 3, 2013 at 17:24
  • Yes, also true for Python. I just wanted to point out that the idea extends beyond C++.
    – duffymo
    Aug 3, 2013 at 17:29
  • So kind of you to say. Thank you.
    – duffymo
    Jun 15, 2018 at 23:01
0

Static binding: if the function calling is known at compile time then it is known as static binding. in static binding type of object matter accordingly suitable function is called. as shown in the example below obj_a.fun() here obj_a is of class A that's why fun() of class is called.

#include<iostream>
using namespace std;
class A{
public:
void fun()
{cout<<"hello world\n";}

};
class B:public A{
public:
void show()
{cout<<"how are you ?\n";}

};

int main()
{
A obj_a;           //creating objects
B obj_b;
obj_a.fun();       //it is known at compile time that it has to call fun()
obj_b.show();     //it is known at compile time that it has to call show()
return 0;
}

dynamic binding: if the function calling is known at run time then it is known as dynamic binding. we achieve late binding by using virtual keyword.as base pointer can hold address of child pointers also. so in this content of the pointer matter.whether pointer is holding the address of base class or child class

#include<iostream>
using namespace std;

class car{
public:
    virtual void speed()
     {
      cout<<"ordinary car: Maximum speed limit  is 200kmph\n";
     }
};
class sports_car:public car{
  void speed()
     {
      cout<<"Sports car: Maximum speed is 300kmph\n";
     }
};

int main()
{
car *ptr , car_obj;      // creating object and pointer to car
sports_car   sport_car_obj;  //creating object of sport_car
ptr = &sport_car_obj;      // assigining address of sport_car to pointer 
                             //object of car 
 ptr->speed();   // it will call function of sports_car

return 0;
}

if we remove virtual keyword from car class then it will call function of car class. but now it is calling speed function of sport_car class. this is dynamic binding as during function calling the content of the pointer matter not the type of pointer. as ptr is of type car but holding the address of sport_car that's why sport_car speed() is called.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.