virtual functions

Total Post:113

Points:791
Java 
 109  View(s)
Ratings:
Rate this:

  What are virtual functions? How do they work?

  1. Post:140

    Points:984
    Re: virtual functions

    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();
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!