Search code examples
c++linkerlinker-errorsvtableundefined-function

returning static member for virtual function, missing vtable for abstract class


Newcomer in cpp here, be advised, possibly dumbness ahead.

I was trying to return a static property when implementing a virtual function. This issue a linker error saying that the function wasn't implemented. I'm lost with this issue.

I was able to reproduce the error with the following stripped down code:

#include <iostream>
#include <map>

class Abstract1 {
public:
    virtual char* getFoo();
};

class Base: public Abstract1 {
public:
    char* getFoo() {
        return Base::mapper[1];
    }
    static std::map<int,char*> mapper;
};

std::map<int, char*> Base::mapper;
int main(int argc, const char * argv[]) {
    Base::mapper[0] = "Hello!\n";
    Base::mapper[1] = "Goodbye!\n";
    Base* hello = new Base();
    // insert code here...
    std::cout << hello->getFoo() << "\n";
    return 0;
}

Yielding the following linker error:

Undefined symbols for architecture x86_64:
  "typeinfo for Abstract1", referenced from:
      typeinfo for Base in main.o
  "vtable for Abstract1", referenced from:
      Abstract1::Abstract1() in main.o

Solution

  • Abstract1::getFoo is simply virtual, not abstract.

    You can either make it abstract : virtual char * getFoo() = 0; or provide a default implementation.