What are virtual functions?
Posted Answers
A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.
Answer by: Anonymous
Basically virtual function is one that support run time polymorphisms.
class a
{
public:
void show();
};
class b: public a
{
public:
void show();
};
here what happens tht function overloading is nt supported as the name of both the functions r same as well as form thus complier cannot differentiate b/w them,thus no static binding take place.
thus to make it work we use virtual function tht helps in dynamic binding at run time.
to expalin virtual function consider an eg:
class a
{int i;
public:
a()//constructor
{ i=0;
}
virtual void show()
{
cout<<"calling base";
cout<
}
void display()
{cout<<"calling base";
}
};
class b:public a
{int j;
public:
b()
{ j=1;
}
void show();
void display();
};
void b:: show()
{
cout<<"calling derived";
cout<
}
void b::display()
{ cout<<"calling der";
}
void main()
{ a a1,*a2;
a2=&a1;
a2->show(); //caliing base
a2->display(); //caliing base
b b1;
a2=&b1;
a2->show();//caliing derived
a2->display();//caliing base
((*b)a2)->display();//caliing derived
getch();
}
virtual function uses pointers.
Answer by: chunilal kukreja
