Static vs dynamic binding

What's the difference between static and dynamic binding. I'm reading my C++ book and can't wrap my head around it. What impact do they have on the behavior of programs at runtime? Also,what impact do they have on the syntax of coding programs?
The easiest answer is that with dynamic linking you are dependent on external libraries for the code to execute and with static linking you are not. Static will (obviously) have a much larger footprint.
Static binding means reference are resolved in compile time, whereas dynamic binding means that references are resolved in run time
When static binding, the choice of which function to call in a class that employs inheritance is made at compile time.

If you use dynamic binding, the choice is made at run time. The program will look up which function to use in a virtual function table, which takes a little time, making dynamic binding slower.
In a very simplified explanation, static binding occurs at compile time, where dynamic binding occurs at run time.

virtual functions are an example of dynamic binding:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Base
{
   public:
     virtual void DoOperation();
}

class Derived: public Base
{
   public:
     void DoOperation(){ cout << "We did it!" << endl; }
}

main
{
//...
   Base * pBase = new Derived();
   pBase->DoOperation(); //dynamic binding, uses virtual table lookup at run time..
//...
}


Static binding occurs at compile time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template <class Derived>
class Base
{
public:
	Base(){};
	void doOperation()
	{
		return static_cast<Derived*>(this)->doStaticOperation();
	}

};

template<class Derived>
class MyClass : public Base<Derived> 
{
public:
	doStaticOperation(){ cout << "We did it statically!" << endl; }
}	
Topic archived. No new replies allowed.