Virtual keyword and function - Object oriented programming (MCQ) questions

1)   Pure virtual function is used
- Published on 19 Oct 15

a. to give meaning to derived class function
b. to give meaning to base class function
c. to initialize all functions
d. None
Answer  Explanation 

ANSWER: to give meaning to base class function

Explanation:
When we use virtual keyword our base class function becomes meaningless as it has no use. It only helps in calling all derived class functions of same name. If base class function is initialized with =0, it is known that function has no body and thus the virtual function of base class becomes pure virtual function.

For example:

class geom
{
public:
virtual void show( )=0;
};

class rect: public geom
{
void show( )
{
cout << " the area is : y" << endl;
}
}


2)   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  Explanation 

ANSWER: all the above

Explanation:
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


1