25.5 — Early binding and late binding

In this lesson and the next, we are going to take a closer look at how virtual functions are implemented. While this information is not strictly necessary to effectively use virtual functions, it is interesting. Nevertheless, you can consider both sections optional reading.

When a C++ program is executed, it executes sequentially, beginning at the top of main(). When a function call is encountered, the point of execution jumps to the beginning of the function being called. How does the CPU know to do this?

When a program is compiled, the compiler converts each statement in your C++ program into one or more lines of machine language. Each line of machine language is given its own unique sequential address. This is no different for functions -- when a function is encountered, it is converted into machine language and given the next available address. Thus, each function ends up with a unique address.

Binding and dispatching

Our programs contain many names (identifiers, keywords, etc…). Each name has a set of associated properties: for example, if the name represents a variable, that variable has a type, a value, a memory address, etc…

For example, when we say int x, we’re telling the compiler to associate the name x with the type int. Later if we say x = 5, the compiler can use this association to type check the assignment to ensure it is valid.

In general programming, binding is the process of associating names with such properties. Function binding (or method binding) is the process that determines what function definition is associated with a function call. The process of actually invoking a bound function is called