Adding a body to a pure virtual / abstract function in C ++?

A pure virtual function should not have a body, but I just noticed that the following code was accepted by the compiler:

class foo
{
    virtual void dummy() = 0
    {
        cout << "hello";
    }
};

So why do pure virtual functions allow you to have a body? Also, even if the function has a body, the class still cannot be created, why?

+4
source share
2 answers

A pure virtual function may have a body, but the fact that you declare them pure virtual is to say that a derived implementation is required .

( BaseClass::method()), .

, . - . , , , .

+5

, / . contract , , .

, , .. = 0.

, , ++ :

, , - . , , .

( ):

...

virtual ~foo() = 0;

...

foo::~foo() {} // required!

, , , foo. , ​​ .

+3

All Articles