Friday, September 2, 2016

Understanding of virtual function

It is a function or method can be overridden within an inheriting class by a function with the same signature ,In other words , the purpose of virtual function is , to allow customization of derived class implementation


   “Where there is a casting there is a virtual”

Base * ptr = new Base() ; //  No need of virtual
Derived * ptr = new Derived();  // No need of virtual
Base * ptr = new Derived(); // need virtual to call correct function

Key benefits of Virtual function :

     It is allowed us to do function over riding
       
    Class Base { virtual void fn1() ; };
    Class derived: public base {void fn1() ;}

   Base* ptr = new derived() ;
    Ptr->fn1() ; this calls the derived class function fn1()

Above class become ptr->_vptr->fn1() ;

Now , consider if fn1() is not declared as virtual , then   the above call would call the Base class function .

Best part of this concepts is , you can have an array ,type of  Base* . and you can append derived classes object without worrying about function call .

 It is avoiding memory leak
  
   lets look at the below code
  
    Class Base { void ~Base() ; };
    Class derived: public base {void ~derived() ;}
   
    Base* ptr = new derived() ;
    delete ptr ;
   oops , there is a memory leak , above call only call base class destructor  .
  
wanna avoid memory leak
  Class Base { virtual void ~Base() ; };

Now , it will use vptr , and it will call the derived class destructor and subsequently it will call base class destructor

Disadvantages or Cost of virtual function

1.      If a class contains virtual function , then vtable is created , which means additional memory space required for that
2.      virtual function are mapped at runtime through vtable . hence calling virtual function is slow compared to normal function
3. vptr (virtual pointer which points to vtable) is created for every object .Additional 4 byte required to store vptr


pictorial representation of virtual function  







At last ,  If a function declared as virtual in base class , then the function in all derived class are virtual only . No need to mention it explicitly using “virtual” keyword


Some FAQ:

  1. What is the size of an empty class
Ans : 1 byte , because compiler provides minimum 1 byte to the object

  1. what is the size of the class  class A { virtual void fn1();};
      Ans : 4 byte ,  now vptr (virtual pointer comes in to the picture)
      
  1. What is pure virtual function
 Ans : A virtual function doesn’t have body
         Virtual void fn1() = 0;

  1. Can we create object of the class which has pure virtual function
Ans : No , Compiler will check the body of the function while creating object of the class , since it doesn’t have the body we can’t create the object and compiler will throw an error at the time of compilation

No comments:

Post a Comment