Virtual Functions – Object Oriented Programming (OOP)

Download our Android App from Google Play Store and start reading Reference Notes Offline.

virtual functionsVirtual Functions – Reference Note
Object Oriented Programming (OOP)
Third Semester | Second year
BSc.CSIT | Tribhuvan University (TU)

Virtual functions
When virtual functions are used, program that appears to be calling a function of one class may in reality be calling a function of different class. They are essential for polymorphism. If a function with a same name exists in base as well as derived class, the pointer to base class would call the functions associated with base class even if its contents are of derived class. To overcome this problem, the function is made virtual in the base class by using the keyword virtual with the function declaration. Virtual function call is resolved at run time and this is known as dynamic binding.
For example

class Base{
public:
virtual void show(){
cout<<”Content of Base class”;
}
};
class deriv1 : public Base{
public:
void show(){
cout<<”Content of derived class1:”;
}
};
Class deriv2 : public Base{
public:
void show(){
cout<<”Content of Derived class2:”;
}
};
void main(){
Deriv1 dv1;
Deriv2 dv2; // If virtual not used, both show “Base”
Base *ptr;
ptr = &dv1;
ptr->show(); // shows “Deriv1”
ptr = &dv2;
ptr->show(); //shows “Deriv2”
}

Posted By : Digvijay | Comment RSS | Category : Third Semester
Tag : ,

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

Wordpress DMCA
Community | Toolbar | Android App | Founder/Developer : Hari Prasad Chaudhary | CSIT Portal Manager : Digvijay Chaudhary