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.

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 following code displays:

  Base: non-virtual function
  Child: virtual function

Related Topics: class