Virtual Function
By
Abdul Wahab
What is Virtual Function?
• A virtual function a member function which is declared with in base class
and is re-defined by a derived class.
• When you refer to a derived class object using a pointer or a reference to the
base class, you can call a virtual function for that object.
Why we use virtual function?
• Virtual function shows that the correct function is called for an object.
• They are mainly used to achieve runtime polymorphism.
• Function are declared with a virtual keyword in base class.
Rules for virtual function.
• Virtual function can not be static and also can not be a friend function of
another class.
• Virtual function should be access using pointer on base class derived to
achieve run time polymorphism
• The prototype of virtual function should be same in base as well as derived
class
Early & Late Binding
• Early Binding: -In early binding, the compiler matches the function call
with the correct function definition at compile time. It is also known
as Static Binding or Compile-time Binding.
• Late Binding:- In the case of late binding, the compiler matches the
function call with the correct function definition at runtime. It is also known
as Dynamic Binding or Runtime Binding.
Working concept of virtual function
p
f2 f3 f4
Vtable
f2 f3 f4
Vtable
p
*_vptr
01
02 //Error
EB
LB
LB
LB
Program of virtual Function
out put

Virtual function complete By Abdul Wahab (moon sheikh)

  • 1.
  • 2.
    What is VirtualFunction? • A virtual function a member function which is declared with in base class and is re-defined by a derived class. • When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object.
  • 3.
    Why we usevirtual function? • Virtual function shows that the correct function is called for an object. • They are mainly used to achieve runtime polymorphism. • Function are declared with a virtual keyword in base class.
  • 4.
    Rules for virtualfunction. • Virtual function can not be static and also can not be a friend function of another class. • Virtual function should be access using pointer on base class derived to achieve run time polymorphism • The prototype of virtual function should be same in base as well as derived class
  • 5.
    Early & LateBinding • Early Binding: -In early binding, the compiler matches the function call with the correct function definition at compile time. It is also known as Static Binding or Compile-time Binding. • Late Binding:- In the case of late binding, the compiler matches the function call with the correct function definition at runtime. It is also known as Dynamic Binding or Runtime Binding.
  • 6.
    Working concept ofvirtual function
  • 7.
  • 8.
    f2 f3 f4 Vtable f2f3 f4 Vtable p *_vptr 01 02 //Error EB LB LB LB
  • 9.
  • 10.