Friday, 24 March 2017

What is a virtual function in derived class in cpp programming

A virtual function is a part function that you hope to be reclassified in derived classes. When you allude to a derived class object utilizing a pointer or a reference to the base class, you can call a virtual function for that protest and execute the derived class' adaptation of the capacity.

A virtual function is a complicated beast and we are not through with it as yet. We know that when we perform inheritance and redefine some of the virtual functions the compiler creates a new VTABLE for the derived class and inserts into it the new function addresses. If in the derived class we do not redefine the virtual functions, then it inserts the base-class function addresses in the derived class's VTABLE. This means there's  always a full set of function address in the VTABLE. Thus a possibility of you calling a function and its address not existing in the VTABLE is ruled out.
Let us now consider a case when we inherit and new virtual functions in the derived class. The following program shows this possibility.

#include <iostream>
using namespace std;

class base
{
public :

virtual void fun1( )
{

cout<<endl<<"in base::fun1";

}
};

class derived : public base
{
public:
void fun1( )
{
cout << endl<< "in derived::fun1";
}
virtual void fun2( )
{
cout << endl<<"in derived::fun2";
}

};

int main( )
{
base*ptr1, *ptr2;
base b;
derived d;
ptr1 = &b;
ptr2 = &d;
ptr1->fun1( );
ptr2->fun1( );
ptr2->fun2( ); //error
return 0;
}

Here the class base contains a single virtual function fun1( ). The derived redefines fun1( ) and adds another virtual function called fun2( ). The VTABLEs created by the compiler for base and derived are shown in the below figure

The compiler would pass the calls  to fun1( ), but it would report an error for the call

ptr2-> fun( ) ;

In this case, the compiler is working only with a pointer to a base class object. The base class doesn't have the fun2( ) function so the compiler cannot allow a call to fun2( ). The compiler doesn't know that you are working with a derived object if it has only a pointer to a base class
object.

The conclusion is that the compiler prevents you from making calls to virtual functions that exist only in derived classes.

1 comments:

Post a Comment