Q19. Explain the virtual functions call mechanism
Answer:
Virtual function call is usually implemented as an indirect function call through a per class table of function that are generated by compiler. Virtual function must be called by specifying objects pointed by the base pointers, so that it determines which function to be invoked. As the virtual function that is defined in base class is not required be to defined in derived class. Otherwise, the virtual function of base class will be used by default in all calls. If a virtual function is called through pointer or reference the actual object type is not known. For this reason, virtual function call mechanism is used.
Syntax
Program
Virtual function call is usually implemented as an indirect function call through a per class table of function that are generated by compiler. Virtual function must be called by specifying objects pointed by the base pointers, so that it determines which function to be invoked. As the virtual function that is defined in base class is not required be to defined in derived class. Otherwise, the virtual function of base class will be used by default in all calls. If a virtual function is called through pointer or reference the actual object type is not known. For this reason, virtual function call mechanism is used.
Syntax
class Base Class
{
public:
virtual void function name() //
Virtual function definition
{
//statements
}
};
main()
{
Base_class pointer object;
pointer object → virtual
function(); //Virtual function Call mechanism
}
In the above Syntax, virtual function is defined in base class. In the main function, the virtual function is called by using base class pointer.Program
#include<iostream.h>
#include<conio.h>
class X
{
int x;
public: 2
X()
{
x=15;
}
virtual void display()
{
cout<<“\n x=”<<x;
}
};
class Y: public X
{
int y;
public:
Y()
{
y = 25;
}
void display()
{
cout<<"\ny="<<y;
}
};
int main()
{
clrscr();
Y k;
b = &a;
b → display();
b = &k;
b → display();
getch();
return 0;
}
Output