Virtual Function definition and example


 

A virtual declared within a base class and isOverride by a derived class. Sometime derived class object using a pointer or a reference to the base class,then due to early binding it always calling base call function.

  • Virtual functions make sure that the correct function is called. 
  • Functions are declared with a virtual keyword in base class.
  • The resolving of function call is done at run time not in compile time.

Keypoints

  1. Virtual functions should not be static or friend function class.
  2. Virtual functions should be accessed using pointer.
  3. A class should not have  virtual constructor.
#include<iostream>
using namespace std;
class base //class 1
{
public:
void print()// function
{
cout<<"This is base class print function:"<<endl;
}
void show()// function
{
cout<<"This is show function in base class "<<endl;
}
};
class derived:public base //class 2
{
public:
void print()
{
cout<<"This is derived class print function:"<<endl;
}
void show()
{
cout<<"This is show function is derived class "<<endl;
}
};
int main()
{
base *b; // pointer of class 1
derived d;// object of class 2
b=&d;// point of class 1 is contain adress of class 2 (class b pointer )b=&(address of class 2)
b->print();// if b contain address of derived class then it show be derived function called
b->show();// due to early binding this is calling base class .. this is a problem.
return 0;// now see second example below
}
view raw .cc hosted with ❤ by GitHub
This is base class  print function:
This is show function is base class
This is problem for early binding.To make sure correct function is working we need late binding to make sure everthing is correct.we use virutal keyword.See below same code with some changes.


#include<iostream>
using namespace std;
class base //class 1
{
public:
virtual void print()// function
{
cout<<"This is base class print function:"<<endl;
}
virtual void show()// function
{
cout<<"This is show function in base class "<<endl;
}
};
class derived:public base //class 2
{
public:
void print()
{
cout<<"This is derived class print function:"<<endl;
}
void show()
{
cout<<"This is show function is derived class "<<endl;
}
};
int main()
{
base *b; // pointer of class 1
derived d;// object of class 2
b=&d;// point of class 1 is contain adress of class 2 (class b pointer )b=&(address of class 2)
b->print();// if b contain address of derived class then it show be derived function called
b->show();// due to early binding this is calling base class .. this is a problem.
return 0;// now see second example below
}
view raw .cc hosted with ❤ by GitHub
This is derived class  print function:
This is show function is derived class

0 Comments