Virtual/pure virtual explained

后端 未结 12 1470
暖寄归人
暖寄归人 2020-11-22 01:31

What exactly does it mean if a function is defined as virtual and is that the same as pure virtual?

12条回答
  •  走了就别回头了
    2020-11-22 02:20

    How does the virtual keyword work?

    Assume that Man is a base class, Indian is derived from man.

    Class Man
    {
     public: 
       virtual void do_work()
       {}
    }
    
    Class Indian : public Man
    {
     public: 
       void do_work()
       {}
    }
    

    Declaring do_work() as virtual simply means: which do_work() to call will be determined ONLY at run-time.

    Suppose I do,

    Man *man;
    man = new Indian();
    man->do_work(); // Indian's do work is only called.
    

    If virtual is not used, the same is statically determined or statically bound by the compiler, depending on what object is calling. So if an object of Man calls do_work(), Man's do_work() is called EVEN THOUGH IT POINTS TO AN INDIAN OBJECT

    I believe that the top voted answer is misleading - Any method whether or not virtual can have an overridden implementation in the derived class. With specific reference to C++ the correct difference is run-time (when virtual is used) binding and compile-time (when virtual is not used but a method is overridden and a base pointer is pointed at a derived object) binding of associated functions.

    There seems to be another misleading comment that says,

    "Justin, 'pure virtual' is just a term (not a keyword, see my answer below) used to mean "this function cannot be implemented by the base class."

    THIS IS WRONG! Purely virtual functions can also have a body AND CAN BE IMPLEMENTED! The truth is that an abstract class' pure virtual function can be called statically! Two very good authors are Bjarne Stroustrup and Stan Lippman.... because they wrote the language.

提交回复
热议问题