virtual function definition

Discussion in 'C++' started by mahati, Oct 5, 2017.

  1. mahati

    mahati New Member

    Joined:
    Jun 30, 2012
    Messages:
    3
    Likes Received:
    1
    Trophy Points:
    1
    According to the definition for virtual function is
    "Virtual functions are member functions whose behavior can be overridden in derived classes. ".What is the meaning of this?

    Also, why virtual function uses pointers?
     
  2. persysweb

    persysweb Member

    Joined:
    Aug 1, 2017
    Messages:
    98
    Likes Received:
    18
    Trophy Points:
    8
    Location:
    India
    Home Page:
    httpS://persys.in/
    A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.

    Virtual functions ensure that the correct function is called for an object, regardless of the expression used to make the function call.

    Suppose a base class contains a function declared as virtual and a derived class defines the same function. The function from the derived class is invoked for objects of the derived class, even if it is called using a pointer or reference to the base class.

    Virtual functions are called only for objects of class types, you cannot declare global or static functions as virtual.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice