title: Linker can't find symbols for static field accessed in virtual class c++
body: <p>I was improving my <strong>visitor pattern</strong> code in <em>c++</em> which originally looked like the code right below, in order to get rid of the unnecessary part where the visitor needs to pass itself to the accept void.</p>
  
  <p>I came up with a simple solution which "turns" the parameter into a <code>static field</code> so I can initialise the field right before I ever use <code>accept</code>.</p>
  
  <p>Forgive me but I need to do this even if it will be very ugly.</p>
  
  <p><strong>Old Code:</strong></p>
  
  <pre class="lang-cpp prettyprint-override"><code>class A_Child;
  class B_Child;
  
  class Father {
      public:
      virtual ~Father() = default;
      class Visitor {
          public:
          virtual void visitChildA(A_Child * child) = 0;
          virtual void visitChildB(B_Child * child) = 0;
      };
      virtual void accept(Visitor * visitor) = 0;
  };
  
  class A_Child: public Father {
      public: /* A Child Stuff */
      void accept(Visitor * visitor) override;
  };
  
  class B_Child: public Father {
      public: /* B Child Stuff */
      void accept(Visitor * visitor) override;
  };
  
  A_Child::accept(Visitor * visitor) { visitor -&gt; visitChildA(this); }
  B_Child::accept(Visitor * visitor) { visitor -&gt; visitChildB(this); }
  
  </code></pre>
  
  <p><strong>New Code:</strong></p>
  
  <pre class="lang-cpp prettyprint-override"><code>class Father {
      public:
      virtual ~Father() = default;
      class Visitor {
          public:
          virtual void visitChildA(A_Child * child) = 0;
          virtual void visitChildB(B_Child * child) = 0;
      };
      static Visitor * visitor;
      virtual void accept() = 0;
  };
  
  // Outside, (assuming NewVisitor: public Father::Visitor):
  
  void NewVisitor::DoStuff(Father * child) {
      Father::visitor = this;
      child -&gt; accept();
  }
  
  </code></pre>
  
  <p><strong>Linker Complaints:</strong></p>
  
  <p>My linker is not happy about it and it gives me the following output:</p>
  
  <pre><code>Undefined symbols for architecture x86_64:
    "Father::visitor", referenced from:
        Child_A::accept() in Father.o
        Child_B::accept() in Father.o
  ld: symbol(s) not found for architecture x86_64
  </code></pre>
  
  <p>Does anyone know why is this happening?
  Am I breaking some mysterious <strong>OOP</strong> rule?</p>