C++ virtual functions implementation outside the class

Even though D derives from B and therefore you can call f() on an instance of D, it does not mean you do not need to put the declaration into the header.

Any function you implement must be explicitly declared in the header.

You do not need, however, to put its implementation in there. Just

class D : public B
{
public:
   /*virtual*/ void f();
};

and you can optionally choose whether to include the word "virtual" here


You can't add members to a class outside of the class definition. If you want D to have an override for B::f then you have to declare it inside the class definition. Those are the rules.

Declaring a member in a base class doesn't automatically give derived classes an identical member. Inheriting from the base gives the derived class all the members of the base class so you can choose whether to override, hide or add to the base classes members but you have to indicate a choice to override in the class definition by declaring the overriding function.