C ++: code explanation for the prototype method with constant = 0

I hava a class declaration with a code snippet that I don't understand:

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

What does the part mean const = 0?

+4
source share
2 answers

This is a pure virtual method ( =0) that should not modify the data of the class ( const). You must provide implementation in one of the classes originating from Weapon! See So: The Difference Between a Virtual Function and a Pure Virtual Function

It is expected that you will receive specific classes Weapon(can be considered an interface), such as Axe, Shotgunetc., where you provide a method attack().

+7
source

const , - , ( mutable ). , , , .

= 0 const. virtual, , . , . , , abstract, .

, Weapon, attack() . , :

class Sword : public Weapon
{
public:
    void attack() const
    {
        // do something...
    }
};
+5

All Articles