virtual function is an implementation of runtime polymorphism. When we declare a pointer of the parent class either assign the address of the base class object irrespective of that when we call the function by using that pointer the it is always call the base class member function even if we assign the address off child class object. What actually happen that when we declare a base class pointer it is associated with the base class member function at the time of compilation by the compiler So, it always call the base class member function .
Example :
class X { public:
void show()
{ cout<<”prakash”; } ;
class Y : public X {
public:
void show() { cout<<”mindstick”; } }; int main() { X *ptr , x1;
Y y1; ptr = &x1; ptr ->show(); ptr = &y1; ptr ->show(); }
To remove this problem we declare the base class member function as virtual by using virtual keyword.
class X {
public:
virtual void show()
{
cout<<”Prakash”;
}
} ;
class Y : public X {
public:
void show()
{
cout<<”Mindstick”;
}
};
int main() {
X *ptr , x1;
Y y1;
ptr = &x1;
ptr ->show();
ptr = &y1;
ptr ->show();
}
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Virtual Function :
virtual function is an implementation of runtime polymorphism. When we declare a pointer of the parent class either assign the address of the base class object irrespective of that when we call the function by using that pointer the it is always call the base class member function even if we assign the address off child class object. What actually happen that when we declare a base class pointer it is associated with the base class member function at the time of compilation by the compiler So, it always call the base class member function .
Example :
class X {
public: void show() {
cout<<”prakash”;
} ; class Y : public X { public: void show()
{
cout<<”mindstick”;
}
};
int main() {
X *ptr , x1; Y y1;
ptr = &x1;
ptr ->show();
ptr = &y1;
ptr ->show();
}
To remove this problem we declare the base class member function as virtual by using virtual keyword.
class X { public: virtual void show() { cout<<”Prakash”; } } ; class Y : public X { public: void show() { cout<<”Mindstick”; } }; int main() { X *ptr , x1; Y y1; ptr = &x1; ptr ->show(); ptr = &y1; ptr ->show(); }