keywords:virtual

C++ Reference

virtual

Syntax:

    virtual return-type name( parameter-list );
    virtual return-type name( parameter-list ) = 0;

The virtual keyword can be used to create virtual functions, which can be overridden by derived classes.

  • A virtual function indicates that a function can be overridden in a subclass, and that the overridden function will actually be used.
  • When a base object pointer points to a derived object that contains a virtual function, the decision about which version of that function to call is based on the type of object pointed to by the pointer, and this process happens at runtime.
  • A base object can point to different derived objects and have different versions of the virtual function run.

If the function is specified as a pure virtual function (denoted by the = 0), it must be overridden by a derived class.

For example, the following code snippet shows how a child class can override a virtual method of its parent, and how a non-virtual method in the parent cannot be overridden:

  class Base {
  public:
   void nonVirtualFunc() {
     cout << "Base: non-virtual function" << endl;
   }
   virtual void virtualFunc() {
     cout << "Base: virtual function" << endl;
   }
  };
 
  class Child : public Base {
  public:
   void nonVirtualFunc() {
     cout << "Child: non-virtual function" << endl;
   }
   void virtualFunc() {
     cout << "Child: virtual function" << endl;
   }
  };
 
  int main() {
   Base* basePointer = new Child();
   basePointer->nonVirtualFunc();
   basePointer->virtualFunc();
   return 0;
  }

When run, the above code displays:

  Base: non-virtual function
  Child: virtual function

Related Topics: class