Virtual/pure virtual explained

后端 未结 12 1463
暖寄归人
暖寄归人 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:21

    In a C++ class, virtual is the keyword which designates that, a method can be overridden (i.e. implemented by) a subclass. For example:

    class Shape 
    {
      public:
        Shape();
        virtual ~Shape();
    
        std::string getName() // not overridable
        {
          return m_name;
        }
    
        void setName( const std::string& name ) // not overridable
        {
          m_name = name;
        }
    
      protected:
        virtual void initShape() // overridable
        {
          setName("Generic Shape");
        }
    
      private:
        std::string m_name;
    };
    

    In this case a subclass can override the the initShape function to do some specialized work:

    class Square : public Shape
    {
      public: 
        Square();
        virtual ~Square();
    
      protected:
        virtual void initShape() // override the Shape::initShape function
        {
          setName("Square");
        }
    }
    

    The term pure virtual refers to virtual functions that need to be implemented by a subclass and have not been implemented by the base class. You designate a method as pure virtual by using the virtual keyword and adding a =0 at the end of the method declaration.

    So, if you wanted to make Shape::initShape pure virtual you would do the following:

    class Shape 
    {
     ...
        virtual void initShape() = 0; // pure virtual method
     ... 
    };
    

    By adding a pure virtual method to your class you make the class an abstract base class which is very handy for separating interfaces from implementation.

提交回复
热议问题