0

I created an interface (only .hpp file):

struct IA
{
public:
    virtual void foo();
};

and a class implementing this interface (.hpp)

class A : public IA
{
    virtual void foo();
}

and .cpp

void A::foo(){...}

this compiles without a problem, but when I use

IA a;

in another file I get this compilation error: "vtable for IA, referenced from: IA::IA() in libSomeOtherFile.a(SomeOtherFile.o) Note: a missing vtable usually means the first non-inline virtual member function has no definition" anyone know why and how do I fix that ?

MichaelB
  • 1,332
  • 1
  • 15
  • 29

2 Answers2

4

If your goal is to make an interface, then you should not be creating an instance of the interface type directly. Use a pointer instead:

IA *a = new A();

Additionally, if it isn't meant to be instantiated then you should make foo pure-virtual in IA:

/* In IA */
virtual void foo() = 0;
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • It worked :) Once I added the = 0 to interface methods I can compile new A(); can anyone please explain why ? – MichaelB Aug 19 '14 at 06:07
  • Quite simply, it works because you are no longer promising to provide an implementation that doesn't exist; instead, now you are telling your compiler explicitly that the implementation won't be provided. – nneonneo Aug 19 '14 at 06:32
1

Do this instead.

struct IA
{
public:
    virtual void foo() { }
};

IA:foo is not a pure virtual function and thus must have an implementation if it's to be overridden in child classes.

Community
  • 1
  • 1
Colin Basnett
  • 4,052
  • 2
  • 30
  • 49