Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Medium

Dynamic Binding in C++

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Binding means linking something to a thing; here, linking is done. In order to learn what dynamic binding is, we should first see what is static binding. Static binding is the binding that can be resolved by a compiler using runtime. This means all the overloaded methods as well as final, static, and private methods are bounded at runtime. So to resolve this problem, the concept of dynamic binding in c++ is created. 

dynamic binding in c++

As we have seen earlier that static binding is done by a compiler using runtime, for preventing this, dynamic binding is delaying the selection or choice of which function to run until its runtime. 

In other words, dynamic binding simply means selecting a particular function to run until the runtime. According to the type of object, the respective function will be called.

What is Dynamic Binding?

Dynamic binding, also known as late binding, is a concept in object-oriented programming where the method to be executed in response to a function call is determined at runtime. Unlike static binding where the method called is determined at compile time, dynamic binding uses object polymorphism to decide which method implementation to execute. It allows for more flexible and reusable code, as the exact type of object may not be known until runtime, and the appropriate method from that object's class is called. This feature is particularly useful in implementing inheritance and polymorphism.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Usage of Dynamic Binding

The process of connecting function calls with function definitions and avoiding static binding issues occurring at runtime is called dynamic binding. Therefore, it can be stated as the connection between function declaration and function call.

Dynamic binding is used in ‘Real Objects’. Dynamic binding is flexible as it enables one function to handle different objects. The overall size of the program can be reduced, and the program is made more readable.

How to Implement Dynamic Binding?

Dynamic binding in C++ can be implemented using virtual functions and polymorphism. Using virtual functions, we can declare a base class (parent class or superclass), and the derived classes can be used to override them.  Virtual functions in C++ are declared within the base class and are overridden by the derived classes.

Static Binding Vs Dynamic Binding 

Dynamic Binding in C++ Static Binding in C++
Dynamic binding in c++ takes place at runtime. Static Binding in C++ takes place at the compile time.
Dynamic Binding is known as late Binding. Static Binding is known as Early Binding.
In Dynamic Binding, function calls are not resolved until runtime. In static Binding, function call and function definition are linked during compile time.
Dynamic Binding occurs when the compiler cannot identify the complete information required for a function call at compile time. Static Binding occurs when the information needed to call a function is available at the compile time.
Dynamic Binding can be obtained using virtual functions. Static Binding can be obtained using the normal function calls, operator overloading, and function overloading.

Virtual Functions

Virtual functions are special member functions to which calls made by pointer/reference are resolved at run time, based on the object type with the pointer. In other words, a virtual function is declared in the base class and overridden in the child class. Now let's see the characteristics of virtual functions:

  • A virtual function cannot be declared as static.
  • Virtual functions are used to obtain runtime polymorphism
  • The virtual function should be defined as the same in the base class as well as the derived class.
  • A virtual function can be a friend of another class.

You can also do a free certification of Basics of C++.

Characteristics of Dynamic Binding in C++

The process when the connection is formed between the function calls with its definition and any static binding issue that occurs during the build time is avoided is known as data binding. Below are some of the characteristics of Dynamic Binding.

  • Dynamic binding occurs at runtime.
     
  • Its execution is slower as compared to the static binding.
     
  • We can achieve dynamic binding through virtual functions. We cannot declare a virtual function as static. The virtual functions are declared within the base class.
     
  • Through Dynamic binding, we can achieve run-time polymorphism. 
     
  • Pointers and references are used in implementing dynamic binding in C++.

Example of Dynamic Binding in C++

Example 1

#include <iostream>  
using namespace std;  
class A {  
public:  
    void closing_print() // function that call display  
    {  
		display();  
    }  
    
    void display() // the display function  
    {  
		cout<< "The Base class function is called" <<endl;  
    }  
}; 
 
class B: public A // B inherit a publicly  
{  
public:  
    void display() // B's display  
    {  
		cout<< "The derived class function is called" <<endl;  
    }  
};  

int main()  
{  
    A obj1; // Creating A's pbject  
    obj1.closing_print(); // Calling final_print  
    B obj2; // calling b  
    obj2.closing_print();  
    return 0;  
}  

 

Output

The Base class function is called
The Base class function is called

 

You can try and compile with the help of online c++ compiler.


Example 2

#include <iostream>  
using namespace std;  
class A {  
	public:  
    void closing_print() // function that call display  
    {  
		display();  
    }  
	
	virtual  void display() // the display function  
    {  
		cout<< "The Base class function is called" <<endl;  
   	}  
};  

class B: public A // B inherit a publicly  
{  
	public:  
   	virtual void display() // B's display  
    {  
		cout<< "The Derived class function is called" <<endl;  
    }  
};  

int main()  
{  
    A obj1; // Creating A's pbject  
    obj1.closing_print(); // Calling final_print  
    B obj2; // calling b  
    obj2.closing_print();  
    return 0;  
}  


Output

The base class function is called
The derived class function is called

Example 3

In this example, we have created a variable x which takes input from the user, and then if we want the square of the number, we have to press 0, and if we want the cube of the number, we have to press 1. This was an example of dynamic binding in C++.

#include <iostream>   
using namespace std;  
int Square(int x)   
{  
    return x * x;  
}  

int Cube(int x)   
{  
    return x * x * x;  
}  

main() {  
    int x;
    cout<<"Enter the value of x:";
    cin>>x;
    int choice;  
    
    do {  
        cout << "Enter 0 for Square value, 1 for Cube value :\n";  
        cin >> choice;  
    }  
    
    while (choice < 0 || choice > 1);  
    int( * ptr)(int);  
    
    switch (choice) {  
        case 0:  
            ptr = Square;  
            break;  
        case 1:  
            ptr = Cube;  
            break;  
    }  
    cout << "The result is :" << ptr(x);  
    return 0;  
}  


Output

Enter the value of x:3
Enter 0 for Square value, 1 for Cube value :
0
The result is:9

 

In this output, we have taken x=3, then pressed 0, giving us the square of the number, i.e., 3.

Frequently Asked Questions

Q. How does the compiler handle dynamic binding in C++?

In C++, the compiler creates a virtual table for classes that contain virtual functions, which contains pointers to the actual function implementations. The virtual table is used for dynamic binding at runtime.

Q. Is C++ dynamic or static?

C++ is a statically typed language, which means the data types must be declared and considered at all times. C++ was designed to be fast and portable like C, along with an easier coding experience.

Q. What is dynamic method binding in OOP?

Dynamic method binding in OOP refers to the process where the method call is resolved at runtime rather than compile time. This allows for more flexible code, enabling polymorphism where the exact method executed depends on the object's runtime type.

Q. Does dynamic binding support polymorphism?

Yes, Polymorphism is supported by Dynamic binding. This can be achieved through virtual functions that make a code more reusable, efficient, adaptable, and flexible. At runtime, an appropriate implementation of a function is usually selected on the basis of the actual object type. Due to this, through a common parent class, the objects of various classes can be used interchangeably.

Conclusion

In this blog, we discussed what is dynamic binding in c++ with the help of examples. We started with the definition of dynamic binding in c++, then we saw the difference between static binding and dynamic binding in c++, and at last, we saw examples of dynamic binding in c++.

If you learn more. you can also refer to our guided path on Coding Ninjas Studio to upskill yourself in Data structure and algorithms, and Competitive Programming.

Recommended Reading:

Do upvote our blogs if you find them helpful and engaging!

Happy learning!

Topics covered
1.
Introduction
2.
What is Dynamic Binding?
3.
Usage of Dynamic Binding
4.
How to Implement Dynamic Binding?
5.
Static Binding Vs Dynamic Binding 
6.
Virtual Functions
7.
Characteristics of Dynamic Binding in C++
8.
Example of Dynamic Binding in C++
8.1.
Example 1
8.2.
Example 2
8.3.
Example 3
9.
Frequently Asked Questions
9.1.
Q. How does the compiler handle dynamic binding in C++?
9.2.
Q. Is C++ dynamic or static?
9.3.
Q. What is dynamic method binding in OOP?
9.4.
Q. Does dynamic binding support polymorphism?
10.
Conclusion