Why do we need virtual functions in C++?

前端 未结 26 3100
北恋
北恋 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++.

提交回复
热议问题