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

后端 未结 3 1412
陌清茗
陌清茗 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:34

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

提交回复
热议问题