Virtual keyword and function

Q.  Virtual keyword is used
- Published on 19 Oct 15

a. to remove static linkages
b. to call function based on kind of object it is being called for
c. to call the methods that don't exist at compile time
d. all the above

ANSWER: all the above
 
All the options are correct as virtual is the keyword used with function of base class then all the functions with same name in derived class, having different implementations are called instead of base class function being called each time.

Compiler creates vtables for each class with virtual function so whenever an object for the virtual classes is created compiler inserts a pointer pointing to vtable for that object. Hence when the function is called the compiler knows which function is to be called actually.

Example:

class geom
{

public:

virtual void show( )
{
cout << ” the area is: x” << endl;
}
};

class rect: public geom
{
void show( )
{
cout << ”the area is: y” << endl;
}
};
int main( )
{
geom* a;
rect b;
a= &b;
a - > show( );
}

output:
the area is: y

Post your comment / Share knowledge


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)