Virtual/pure virtual explained

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

提交回复
热议问题