C++ header file and function declaration ending in "= 0"

Adam picture Adam · Mar 26, 2010 · Viewed 20.7k times · Source

I have the following code inside the .h file and I'm not sure what does the assignment statement do and how is it called properly?

virtual void yield() = 0;

I thought that the function returns a value of 0 by default but since this function returns void I am a little bit confused. Can anyone comment on this and maybe say how can I refer to this assignment, I mean how is it called in C++ jargon?

Thanks.

Answer

Björn Pollex picture Björn Pollex · Mar 26, 2010

This is a pure virtual function. This means, that subclasses have to implement this function, otherwise they are abstract, meaning you cannot create objects of that class.

class ISomeInterface {
public:
    virtual std::string ToString( ) = 0;
}

class SomeInterfaceImpl : public ISomeInterface {
public:
    virtual std::string ToString( ) {
        return "SomeInterfaceImpl";
    }
}

The idea is, that a class can expose a certain method, but subclasses have to implement it. In this example, ISomeInterface exposes a ToString method, but there is no sensible default implementation for that, so it makes the method pure virtual. Subclasses like SomeInterfaceImpl can then provide a fitting implementation.