Switch to full style
For C/C++ coders discussions and solutions
Post a reply

What are Virtual Functions?

Wed Jul 04, 2007 12:32 am

What are Virtual Functions? How to use the virtual functions in C++?
---------------------------------------------


Virtual Functions are the basis of Polymorphism concept as they provide the mechanics of late binding. A class, which has at least one function declared as Virtual has a V-Table associated with it. V-Table maintains pointers of all the Virtual functions of that class. Virtual functions are marked using Virtual keyword.

All objects of that class point to the same V-Table. Whenever there is a call made to a function which is virtual, the pointer to that function is obtained during runtime from the V-Table. Hence there is dynamic binding or late binding that leads to the function of the derived class getting called.

Code Example:
cpp code
class Shape  
{
public:
virtual void Draw() // virtual function for C++ virtual function example
{
cout <<"I am class Shape";
}
};

class Line : public Shape
{
public:
void Draw()
{
cout<<"I am line class - Overridden virtual function";
}
};

void main()
{
Shape *x, *y;

x = new Shape();
x->Draw();

y = new Line();
y->Draw();
}


The output is :
Code:
I am  class Shape
I am line class - Overridden   virtual function




Re: What are Virtual Functions?

Wed Jan 23, 2013 11:50 pm

updated.

Post a reply
  Related Posts  to : What are Virtual Functions?
 What are Inline functions?     -  
 Functions and References     -  
 PHP Array Functions     -  
 using of scanf and printf functions     -  
 Calling Functions Dynamically     -  
 Need help about Enhanced Virtual Executor (EVE)     -  
 Virtual Reality Applications     -  
 softwares of virtual reality     -  
 transferring presentation on virtual classroom     -  

Topic Tags

C++ OOP