-2

The following code doesn't compile and I am not quite sure I understand why:

class A {
public:
    virtual ~A() {}
};

class B : public A {
public:
    virtual ~B() {}
    static B* I() { return &i_; }

protected:
    static B i_;
    explicit B() {}
};

int main() {
    A* a = B::I();
    (void)a;
    return 0;
}

Undefined symbols for architecture x86_64:
  "B::i_", referenced from:
      B::I() in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

The symbol should be accessible to the I() method, but it's not.

Apple LLVM version 9.1.0 (clang-902.0.39.2)

John Difool
  • 5,572
  • 5
  • 45
  • 80

1 Answers1

2

Add this to your .cpp's global scope to define the i_ static member:

B B::i_;
cfillion
  • 1,340
  • 11
  • 16