need of vfunction

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sandeep kumar mall
    New Member
    • Dec 2007
    • 1

    #1

    need of vfunction

    what's the need of virtual function, please tell me as soon
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    In C++ you can have inheritance. There you have the base class and the derived class.

    The derived class can override a base class method. So, when you use a deirved object, you call the derived method and when you have a base object you call the base method.

    However, since the derived object IS-A-KIND-OF base object (due to inheritance), you can use the derived object in place of a base object.

    That means you can use the derived object to call a function expecting a base object. Like this:

    [code=cpp]
    void Show(Base& s)
    {
    s.draw();
    }
    int main()
    {
    Derived obj;
    Show(obj);
    }
    [/code]

    When you are inside the Show function, you see a call to a Base class draw() method. That will call the base class draw() method when, in fact, it should be the derived class draw() method that is called since the object really is a derived object.

    The compiler has a choice. It can call the Base draw() method since the Show function argument is a Base class reference, or it can call the derived class draw() method since the object is really a derived object.

    You tell the compiler to call the derived class draw() method by making the base class draw() method virtual. Otherwise, the compiler will call the base class draw() method.

    In other words, virtual functions is how object-oriented programming is implemented in C++.

    Comment

    • abhisoni
      New Member
      • Dec 2007
      • 12

      #3
      Plz follow to these links and you'll get the ans to almost all your VFuntions related queries....

      Links to other sites are not allowed - please read the Posting Guidelines

      Do let me know whether it was of any help.

      Comment

      Working...