Total members 11895 |It is currently Sat Dec 21, 2024 3:36 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





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




_________________
Please recommend my post if you found it helpful


Author:
Beginner
User avatar Posts: 109
Have thanks: 5 time

updated.

_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time
Post new topic Reply to topic  [ 2 posts ] 

  Related Posts  to : What are Virtual Functions?
 What are Inline functions?     -  
 Functions and References     -  
 PHP Array Functions     -  
 Virtual Reality Applications     -  
 softwares of virtual reality     -  
 using of scanf and printf functions     -  
 Calling Functions Dynamically     -  
 Need help about Enhanced Virtual Executor (EVE)     -  
 Lets Learn C++----->(Lesson 5) Functions     -  



Topic Tags

C++ OOP






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com