What is virtual function in c++

Polymorphism refers to the property by which objects belonging to different classes are able to respond to the same message, but in different forms. An essential requirement of polymorphism is therfore the ability to refer to object without any regards to their classes. This necessities the use of a single pointer variable to refer to the objects of different classes.

Here, we use pointers to base class to refer to all the derived objects. But, we just discovered that a base pointer, even when it is made to contain the address of a derived class, always executes the function in a base class. The compiler simply ignores the content of the pointer and chooses the member function that matches the type of pointer. How do we then achieve polymorphism? it is achieved using what is known as Virtual function.

Virtual function details

When we use the same function name in both the base and derived classes, the function in base class is declared as virtual using keyword virtual preceding its normal declaration . When a function is made virtual, C++ determines which function to use at run time based on the type of object pointed by the base pointer, rather than the type of the pointer. Thus, by making the base pointer to point to different objects, we can execute different versions of the virtual function.

// Virtual-funtion

#include <iostream>
using namespace std;

class Base{
public:
void display(){
cout<< "\n DISPLAY base";
} virtual void show(){
cout << "\n show base";
}
};

class Derived : public Base{
public:
void display()
{
cout <<"\n DIPSLAY derived";
}
void show(){
cout << "\n show derived";
}
};

int main()
{
Base B;
Derived D;
Base *bptr;
cout << "\n bptr points to base \n";
bptr = &B;
bptr-> display(); //calls base version
bptr-> show(); //calls abse version

cout << "\n bptr points to derived \n"; bptr= &D;
bptr-> display(); // calls derived version
bptr-> show(); //calls derived version
return 0;
}
Output:
bptr points to base
Display base
Show base
bptr points to Derived
Display base
Show derived

Note:

When bptr is made to point to the object D, the statement
bptr-> display();
calls only the function associated with the Base(i.e, Base::display()), Whereas the statement
bptr->show();
calls the derived version to show(). This is because the funtion display() has not been made virtual in the Base class.

One of the important point to remember is that, we must access virtual function through the use of a pointer declared as a pointer to the abse class. Why can't we use object name (with the dot operator) the same way as any other member function to cal the virtual function? We can't, but remember, run time polymorphsim is achieved only when a virtual fucntion is accessed through a pointer to the base class.


virtual function and runtime polymorphism related image in c++

Runtime Polymorphism

//Runtime-polymorsphism

#include <iostream>
using namespace std;

class media{
protected:
char title[50];
float price;
public:
media(char *s, float a){
srtcpy(title, s);
price = a;

}
virtual void display(){ }
// empty virtual function };

class book: public media{
int pages;
public:
book(char *s, float a, int p) : media(s,a)
{
pages = p;
}
void display(){ }
};

class tape: public media{
float time;
public:
tape(char *s, float a, float t) : media(s,a)
{
time=t;
}
void display(){ };
}; void book:: display()
{
cout <<"\n Title:">>title; cout <<"\n Pages:">>pages; cout <<"\n Price:">>price;
}
void tape:: display()
{
cout <<"\n Title:">>title; cout <<"\n Play Time:">>time>>mins; cout <<"\n Price:">>price;
}

int main()
{
char *title = new char[30];
float price, time;
int pages;
//Book details
cout <<"\n ENTER BOOK DETAILS\n";
cout <<"Title:"; cin>> title;
cout <<"Price:"; cin>> price;
cout <<"pages:"; cin>> pages;

book book1(title, price, pages)
// Tape details
cout<<"\n ENTER TAPE DETAILS\n";
cout<<"Title:";cin>> title;
coyt<<"Price:"; cin>> price;
cout<<"PLay time (mins):"; cin>> time;
tape taprl(title, price, time);

media* list[2];
list[0]= &book1;
list[1]=&tape1;
cout<< "\n MEDIA DETAILS";

cout<<"\n ......BOOK........";
list[0] -> display(); //display book details
cout<<"\n..... TAPE.....";
list[1] -> display(); //display tape details
return 0;
}
Output:
ENTER BOOK DETAILS
Title:Programming_in_ANSI_C
Price: 88
Pages: 400

ENTER TAPE DETAILS
Title: Computing_concepts
Price:90
Play time (mins):55

MEDIA DETAILS
.......BOOK......
Title:Programming_in_ANSI_C
Pages: 400
Price: 88

......TAPE...... Title: Computing_concepts
Play time: 55mins
Price:90

Rules for virtual functions

When virtual functions are created implementing late binding, we should observe some basic rules that stisfy the compiler requirements:

  1. The virtual functions must be member of some class.
  2. They cannot be static members.
  3. They are accessed by using object pointers.
  4. A virtual function can be friend of another class.
  5. A vitual fucntion in a base class must be defined, even though it may not be used
  6. The prototypes of the base class version of a virtual function and all derived class versions must be identical. if two functions with the same name have different prototypes, C++ considered them as overloaded function, and the virtual function mechanism is ignored.
  7. We cannot have virtual constuctors, but we can have virtual destructors.
  8. While a base pointers can point to any type of the derived object, the reverse is not true. That is to say, we cannot use a pointer to a derived class to access an object of the base type.
  9. When a base pointer point to a derived class, incrementing or decrementing it will not make it to pont to the next object of the derived class. it is incemented to all decremented only relative to its base type. Therefore, we should not use this method to move the pointer to the next object.
  10. If a virtual function is deifned in the base class, it need not be necessarily redefined in the derived class. In suh cases, call will invoke the base function.

Post a Comment

1 Comments