Why do we need virtual functions in C++?

前端 未结 26 3165
北恋
北恋 2020-11-21 05:50

I\'m learning C++ and I\'m just getting into virtual functions.

From what I\'ve read (in the book and online), virtual functions are functions in the base class that

相关标签:
26条回答
  • 2020-11-21 06:17

    Without "virtual" you get "early binding". Which implementation of the method is used gets decided at compile time based on the type of the pointer that you call through.

    With "virtual" you get "late binding". Which implementation of the method is used gets decided at run time based on the type of the pointed-to object - what it was originally constructed as. This is not necessarily what you'd think based on the type of the pointer that points to that object.

    class Base
    {
      public:
                void Method1 ()  {  std::cout << "Base::Method1" << std::endl;  }
        virtual void Method2 ()  {  std::cout << "Base::Method2" << std::endl;  }
    };
    
    class Derived : public Base
    {
      public:
        void Method1 ()  {  std::cout << "Derived::Method1" << std::endl;  }
        void Method2 ()  {  std::cout << "Derived::Method2" << std::endl;  }
    };
    
    Base* obj = new Derived ();
      //  Note - constructed as Derived, but pointer stored as Base*
    
    obj->Method1 ();  //  Prints "Base::Method1"
    obj->Method2 ();  //  Prints "Derived::Method2"
    

    EDIT - see this question.

    Also - this tutorial covers early and late binding in C++.

    0 讨论(0)
  • 2020-11-21 06:17

    It helps if you know the underlying mechanisms. C++ formalizes some coding techniques used by C programmers, "classes" replaced using "overlays" - structs with common header sections would be used to handle objects of different types but with some common data or operations. Normally the base struct of the overlay (the common part) has a pointer to a function table which points to a different set of routines for each object type. C++ does the same thing but hides the mechanisms i.e. the C++ ptr->func(...) where func is virtual as C would be (*ptr->func_table[func_num])(ptr,...), where what changes between derived classes is the func_table contents. [A non-virtual method ptr->func() just translates to mangled_func(ptr,..).]

    The upshot of that is that you only need to understand the base class in order to call the methods of a derived class, i.e. if a routine understands class A, you can pass it a derived class B pointer then the virtual methods called will be those of B rather than A since you go through the function table B points at.

    0 讨论(0)
  • 2020-11-21 06:17

    We need virtual methods for supporting "Run time Polymorphism". 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.

    0 讨论(0)
  • 2020-11-21 06:19

    I would like to add another use of Virtual function though it uses the same concept as above stated answers but I guess its worth mentioning.

    VIRTUAL DESTRUCTOR

    Consider this program below, without declaring Base class destructor as virtual; memory for Cat may not be cleaned up.

    class Animal {
        public:
        ~Animal() {
            cout << "Deleting an Animal" << endl;
        }
    };
    class Cat:public Animal {
        public:
        ~Cat() {
            cout << "Deleting an Animal name Cat" << endl;
        }
    };
    
    int main() {
        Animal *a = new Cat();
        delete a;
        return 0;
    }
    

    Output:

    Deleting an Animal
    
    class Animal {
        public:
        virtual ~Animal() {
            cout << "Deleting an Animal" << endl;
        }
    };
    class Cat:public Animal {
        public:
        ~Cat(){
            cout << "Deleting an Animal name Cat" << endl;
        }
    };
    
    int main() {
        Animal *a = new Cat();
        delete a;
        return 0;
    }
    

    Output:

    Deleting an Animal name Cat
    Deleting an Animal
    
    0 讨论(0)
  • 2020-11-21 06:20

    If the base class is Base, and a derived class is Der, you can have a Base *p pointer which actually points to an instance of Der. When you call p->foo();, if foo is not virtual, then Base's version of it executes, ignoring the fact that p actually points to a Der. If foo is virtual, p->foo() executes the "leafmost" override of foo, fully taking into account the actual class of the pointed-to item. So the difference between virtual and non-virtual is actually pretty crucial: the former allows runtime polymorphism, the core concept of OO programming, while the latter does not.

    0 讨论(0)
  • 2020-11-21 06:20

    Virtual methods are used in interface design. For example in Windows there is an interface called IUnknown like below:

    interface IUnknown {
      virtual HRESULT QueryInterface (REFIID riid, void **ppvObject) = 0;
      virtual ULONG   AddRef () = 0;
      virtual ULONG   Release () = 0;
    };
    

    These methods are left to the interface user to implement. They are essential for the creation and destruction of certain objects that must inherit IUnknown. In this case the run-time is aware of the three methods and expects them to be implemented when it calls them. So in a sense they act as a contract between the object itself and whatever uses that object.

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