Virtual functions
A virtual function is a member function declared in a base class and re-declared in a derived class (overridden). You can execute the virtual function of the derived class when you refer to its object using a pointer or reference to the base class. The concept of dynamic binding is implemented with the help of virtual functions.
Example:
C++
// C++ Program to Demonstrate the implementation of Dynamic // Binding without the help of Virtual Function #include <bits/stdc++.h> using namespace std; class GFG { public : void Add( int gfg1, int gfg2) // Function Definition { cout << gfg1 + gfg2 << endl; return ; } // Function Definition void Sub( int gfg1, int gfg2) { cout << gfg1 - gfg2; } }; int main() { GFG gfg; gfg.Add(10, 12); gfg.Sub(12, 10); return 0; } |
22 2
Example:
C++
// C++ Program to Demonstrate the Concept of Dynamic binding // with the help of virtual function #include <iostream> using namespace std; class GFG { public : // function that call print void call_Function() { print(); } // the display function virtual void print() { cout << "Printing the Base class Content" << endl; } }; // GFG2 inherited publicly class GFG2 : public GFG { public : void print() // GFG2's display { cout << "Printing the Derived class Content" << endl; } }; int main() { GFG w3wiki; // Creating GFG's object w3wiki.call_Function(); // Calling call_Function GFG2 w3wiki2; // calling GFG2 w3wiki2.call_Function(); return 0; } |
Printing the Base class Content Printing the Derived class Content
Dynamic Binding in C++
Dynamic binding in C++ is a practice of connecting the function calls with the function definitions by avoiding the issues with static binding, which occurred at build time. Because dynamic binding is flexible, it avoids the drawbacks of static binding, which connected the function call and definition at build time.
In simple terms, Dynamic binding is the connection between the function declaration and the function call.
So, choosing a certain function to run up until runtime is what is meant by the term Dynamic binding. A function will be invoked depending on the kind of item.