What is early (static) and late (dynamic) binding in C++?

后端 未结 3 1436
陌清茗
陌清茗 2020-12-29 04:00

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 re

3条回答
  •  心在旅途
    2020-12-29 04:22

    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 func =
            op == '+' ? std::unique_ptr{new Add{}}
                      : std::unique_ptr{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.

提交回复
热议问题