c++ static binding

Author of the article: Caspian
Source Website: https://blog.csdn.net/WangPaiFeiXingYuan


Introduction:

        Static Binding in C++ refers to the way of binding at compile time, also known as early binding or static polymorphism (Static Polymorphism).

        In static binding, the call and binding of the function have been determined at compile time, that is to say, the call and binding of the function have nothing to do with the object type, and the compiler will determine what should be called according to the pointer or reference type of the function. which function.

        The advantage of static binding is that the compiler can find some type errors in advance, and the overhead of the program runtime is small. However, static binding also has disadvantages. It lacks dynamism, and cannot dynamically change the calling relationship of functions during runtime, nor can it achieve polymorphism.

     

Here is an example of static binding:

#include <iostream>  
using namespace std;  
  
class Base 
{  
public:  
    virtual void print() 
    {  
        cout << "This is Base class" << endl;  
    }  
};  
  
class Derived : public Base 
{  
public:  
    void print() 
    {  
        cout << "This is Derived class" << endl;  
    }  
};  
  
int main() 
{  
    Base *b;  
    Derived d;  
    b = &d;  
    b->print(); // 静态联编,调用Derived类的print函数  
    return 0;  
}

        In the above example, when calling the print function through the pointer of the Base class, since the pointer type is the Base class, the compiler will call the print function of the Base class according to the pointer type. However, since the Derived class covers the print function of the Base class, the print function of the Derived class is actually called. This is how static binding is implemented.

Guess you like

Origin blog.csdn.net/WangPaiFeiXingYuan/article/details/131429059