Search code examples
c++polymorphismvirtual-functions

Why do we need virtual functions in C++?


From what I've read, virtual functions are functions in the base class that you can override in its derived classes.

But earlier, when learning about basic inheritance, I was able to override base functions in derived classes without using virtual.

What am I missing here? I know there is more to virtual functions, and it seems to be important so I want to be clear on what it is exactly.


Solution

  • 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 () override {  std::cout << "Derived::Method2" << std::endl;  }
        // Note - override is optional; adding it to Method1 would result in an error
    };
    
    Base* basePtr = new Derived ();
    // Note - constructed as Derived, but pointer stored as Base*
    
    basePtr->Method1 ();  //  Prints "Base::Method1"
    basePtr->Method2 ();  //  Prints "Derived::Method2"
    

    See Also