0

I am new to C++ and when I try to run this program it tells me: "error LNK2001: unresolved external symbol "private: static int Plate::plate_nID". I am right now just trying to create the plate class and print out the ID. Not sure where I went wrong.

#pragma once
#include <string>

using namespace std;

class Plate{
   private:
      int id;
      string plateName;
      static int plate_nID;

      int generateID(){
         plate_nID++;
         return plate_nID;
      }
   public:
      Plate(string name){
         plateName = name;
         id = generateID();
      }
      ~Plate(){}
      int getID(){
         return id;
      }
      string getName(){
         return plateName;
      }
};

Here is my main:

#include "Plate.cpp"
#include "PlateNode.cpp"
using namespace std;

int main(){
Plate s=Plate::Plate("p1");
cout << s.getID();}

I have looked at this question: Undefined reference to static class member which similar questions to mine were marked as dulpicates of, but I when I try to do that it tells me: cannot instantiate non-static member outside of class. Please Help!

Community
  • 1
  • 1

2 Answers2

1

You need to define the static variable outside your class, only then will your code work

int Plate::plate_nID = 0;

You must define it outside the class (preferably outside the main() )

Probably better to define it right after your class.

Arun A S
  • 6,421
  • 4
  • 29
  • 43
0

You need to define the static member variable outside the class. Something along the lines of:

int Plate::plate_nID = 0;
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • @ChrisMurphy, It has to be outside the class, in a .cpp file. – R Sahu Feb 05 '15 at 04:45
  • I tried to put it inside the Plate.cpp filw but then when I try to instantiate a plate in the main file it says plate_nID already defined – Chris Murphy Feb 05 '15 at 04:47
  • You should not `#include` a .cpp file in another .cpp file. `#include` only .h files. Compile the .cpp files separately and link the resulting object files to create an executable. – R Sahu Feb 05 '15 at 04:48