Interview Questions   Tutorials   Discussions   Programs   Videos   

C++ - What is virtual function?




275
views
asked marvit August 18, 2014 12:26 PM  

What is virtual function?


           

1 Answers



 
answered By bhjahnavi   0  
A virtual function is a member function that you expect to be redefined in derived classes. 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 and execute the derived class's version of the function.
for example:
/*an example program to demonstrate virtual function*/
#include<iostream.h>
Class A 
{ 
    int a; 
    public: 
    A() 
    {
         a = 1; 
    } 
    virtual void show() 
    { 
          cout <<a;
    } 
};

Class B: public A 
{ 
     int b; 
     public: 
     B() 
     { 
         b = 2; 
     }
     virtual void show() 
     { 
         cout <<b;
     }
};

int main() 
{ 
      A *pA; 
      B oB; 
      pA = &oB; 
      pA->show(); 
      return 0; 
}
flag   
   add comment

Your answer

Join with account you already have

FF

Preview


Ready to start your tutorial with us? That's great! Send us an email and we will get back to you as soon as possible!

Alert