-5

Say I have an interface defined as:

class MyInterface : public virtual ObjectInterface {
 public:

   virtual bool MyFunc() = 0;
};

Then I have a class which adopts this interface, in the header file:

class Concrete : public virtual MyInterface, public Object {

};

Then in the implementation file I have:

bool Concrete::MyFunc() {
    return false;
}

Why do I get the error: Out of line declaration? I've tried adding const and override to the implementation but get a similar error.

Clip
  • 3,018
  • 8
  • 42
  • 77
  • 3
    Seems like you need [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jesper Juhl May 13 '19 at 17:36
  • 6
    You missed to put `bool MyFunc();` in your `Concrete` class declaration, that's why. – πάντα ῥεῖ May 13 '19 at 17:37
  • @πάνταῥεῖ kinda makes the interface a bit useless IMO. C++ smh. – Clip May 13 '19 at 17:38
  • why does `MyInterface` virtually inherit from some unknown `ObjectInterface`? – user7860670 May 13 '19 at 17:40
  • 2
    @Clip _"kinda makes the interface a bit useless IMO. C++ smh."_ How so?? – πάντα ῥεῖ May 13 '19 at 17:40
  • 3
    The compiler needs to know in the class definition whether you're going to override each virtual function or not. Not declaring an override means that the class uses the same function from its base class. And if the function is pure virtual in the base, that means the derived class also ends up abstract, not concrete. – aschepler May 13 '19 at 17:41
  • Inheritance is not a quick way to save keystrokes. You may find that an interface isn't useful and sometimes misleading or an [outright bad idea](https://stackoverflow.com/questions/56860/what-is-an-example-of-the-liskov-substitution-principle). – user4581301 May 13 '19 at 19:22

1 Answers1

3

You must declare all member functions within the class definition. You cannot define a member function after the class definition unless the function has been declared inside the definition.

Whether the member function overrides a (pure) virtual function from a base class makes no difference in this regard.

In this case:

class Concrete : public virtual MyInterface, public Object {
    bool MyFunc() override;
};
eerorika
  • 232,697
  • 12
  • 197
  • 326