Virtual/pure virtual explained

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

    The virtual keyword gives C++ its' ability to support polymorphism. When you have a pointer to an object of some class such as:

    class Animal
    {
      public:
        virtual int GetNumberOfLegs() = 0;
    };
    
    class Duck : public Animal
    {
      public:
         int GetNumberOfLegs() { return 2; }
    };
    
    class Horse : public Animal
    {
      public:
         int GetNumberOfLegs() { return 4; }
    };
    
    void SomeFunction(Animal * pAnimal)
    {
      cout << pAnimal->GetNumberOfLegs();
    }
    

    In this (silly) example, the GetNumberOfLegs() function returns the appropriate number based on the class of the object that it is called for.

    Now, consider the function 'SomeFunction'. It doesn't care what type of animal object is passed to it, as long as it is derived from Animal. The compiler will automagically cast any Animal-derived class to a Animal as it is a base class.

    If we do this:

    Duck d;
    SomeFunction(&d);
    

    it'd output '2'. If we do this:

    Horse h;
    SomeFunction(&h);
    

    it'd output '4'. We can't do this:

    Animal a;
    SomeFunction(&a);
    

    because it won't compile due to the GetNumberOfLegs() virtual function being pure, which means it must be implemented by deriving classes (subclasses).

    Pure Virtual Functions are mostly used to define:

    a) abstract classes

    These are base classes where you have to derive from them and then implement the pure virtual functions.

    b) interfaces

    These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.

    0 讨论(0)
  • 2020-11-22 02:12
    • Virtual functions must have a definition in base class and also in derived class but not necessary, for example ToString() or toString() function is a Virtual so you can provide your own implementation by overriding it in user-defined class(es).

    • Virtual functions are declared and defined in normal class.

    • Pure virtual function must be declared ending with "= 0" and it can only be declared in abstract class.

    • An abstract class having a pure virtual function(s) cannot have a definition(s) of that pure virtual functions, so it implies that implementation must be provided in class(es) that derived from that abstract class.

    0 讨论(0)
  • 2020-11-22 02:17

    Simula, C++, and C#, which use static method binding by default, the programmer can specify that particular methods should use dynamic binding by labeling them as virtual. Dynamic method binding is central to object-oriented programming.

    Object oriented programming requires three fundamental concepts: encapsulation, inheritance, and dynamic method binding.

    Encapsulation allows the implementation details of an abstraction to be hidden behind a simple interface.

    Inheritance allows a new abstraction to be defined as an extension or refinement of some existing abstraction, obtaining some or all of its characteristics automatically.

    Dynamic method binding allows the new abstraction to display its new behavior even when used in a context that expects the old abstraction.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 02:22

    A virtual function is a member function that is declared in a base class and that is redefined by derived class. Virtual function are hierarchical in order of inheritance. When a derived class does not override a virtual function, the function defined within its base class is used.

    A pure virtual function is one that contains no definition relative to the base class. It has no implementation in the base class. Any derived class must override this function.

    0 讨论(0)
提交回复
热议问题