c++ : code explanation for method prototype with const = 0

Jérémy Pouyet picture Jérémy Pouyet · Jan 17, 2014 · Viewed 14.4k times · Source

I hava a class declaration with a piece of code that I do not understand :

class Weapon
{
  public:
    virtual void attack() const = 0;
};

What does the const = 0 part means ?

Answer

Ferenc Deak picture Ferenc Deak · Jan 17, 2014

This is a pure virtual method (=0) which is not supposed to change the data of the class (const). You should provide an implementation in one of the classes deriving from Weapon! See this: Difference between a virtual function and a pure virtual function

You are expected to derive from the Weapon (can be considered interface) concrete classes, such as Axe , Shotgun, etc ... where you will provide the attack() method.