Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How one can achieve late binding in C language?

How one can achieve late binding in C language ?

like image 370
cppdev Avatar asked Jan 18 '10 11:01

cppdev


People also ask

What is late binding in C?

Late binding is also called dynamic binding. Late binding occurs when we make implicit or indirect function calls in our program. An example of this is using function pointers or virtual functions when using classes. Here, the function call's memory reference is not determined at compile-time, but rather at run-time.

Which one is the way C++ provides late binding?

In C++, one way to get late binding is to use function pointers. To review function pointers briefly, a function pointer is a type of pointer that points to a function instead of a variable. The function that a function pointer points to can be called by using the function call operator (()) on the pointer.

What is late binding with example?

Basically, late binding is achieved by using virtual methods. The performance of late binding is slower than early binding because it requires lookups at run-time. Example: In the below, program the obj holds integer type data and obj1 holds double type data. But the compiler doesn't resolve these at compile-time.

Which function is used for late binding?

This is run time polymorphism. In this type of binding the compiler adds code that identifies the object type at runtime then matches the call with the right function definition. This is achieved by using virtual function.


1 Answers

Late binding is not really a function of the C language itself, more something that your execution environment provides for you.

Many systems will provide deferred binding as a feature of the linker/loader and you can also use explicit calls such as dlopen (to open a shared library) and dlsym (to get the address of a symbol within that library so you can access it or call it).

The only semi-portable way of getting late binding with the C standard would be to use some trickery with system() and even that is at least partially implementation-specific.

If you're not so much talking about deferred binding but instead polymorphism, you can achieve that effect with function pointers. Basically, you create a struct which has all the data for a type along with function pointers for locating the methods for that type. Then, in the "constructor" (typically an init() function), you set the function pointers to the relevant functions for that type.

You still need to include all the code even if you don't use it but it is possible to get polymorphism that way.

like image 94
paxdiablo Avatar answered Oct 27 '22 00:10

paxdiablo