0

I am learning C++ and have a weird issue with a lab I am working on. Where I don't seem to be referencing things right would be my guess.

It basically throws an error like it can't find the static int nCounters declared in the Class Header file.

//Start of counter.h

class Counter
{

private:
  int counter;
  int limit;
  static int nCounters;

public:
  Counter(int x, int y);
  void increment();
  void decrement();
  int getValue();
  int getNCounters();

};

//end of counter.h

//Start of counter.cpp

#include "counter.h"

Counter::Counter(int x, int y)
{
    counter = x;
    limit = y;
    nCounters++;
}

void Counter::increment()
{
    if (counter < limit)
    {
        counter++;
    }
}

void Counter::decrement()
{
    if (counter > 0)
    {
        counter--;
    }
}

int Counter::getValue()
{
    return counter;
}

int Counter::getNCounters()
{
    return nCounters;
}

//end of counter.cpp

//Start of counter_test.cpp

#include <iostream>
#include "counter.cpp"
using namespace std;
int main(){
    Counter derp(5,5);

    cout << derp.getValue();

    return 0;
}

//end of counter_test.cpp

Tim Herbert
  • 120
  • 10
  • If I remove static it compiles and runs just fine. It must be something I don't understand here. – Tim Herbert Feb 21 '18 at 01:05
  • There are dozens if not hundreds of answered Stack Overflow questions found by a search like "C++ undefined reference static member". – aschepler Feb 21 '18 at 01:12
  • @aschepler Google search for *undefined reference static variable c++ site:stackoverflow.com* says "About 48,200 results" – user4581301 Feb 21 '18 at 01:13

2 Answers2

1

You need to define the static variable. static int nCounters; is just a declaration not definition.

Define like this

int Counter :: nCounters;

for e.g

class Counter {
        private:
                static int nCounters; /*declaration */
        public:
                /* Member function of class */
};
int Counter :: nCounters;/*definition, this is must  */
int main() {
        /* some code **/
        return 0;
}
Achal
  • 11,821
  • 2
  • 15
  • 37
  • Awesome works perfectly after adding this in my counter.cpp file. I knew I must have been missing something somewhere. – Tim Herbert Feb 21 '18 at 01:25
1

As this variable is the same across all classes and is not defined when you instantiate a Counter unlike normal member variables, you have to add the following line somewhere in your code (Best placed in counter.cpp):

Counter::nCounters = 0;

This sets the defines and sets the initial value of nCounters.

On a side note, #include "counter.cpp" is bad practice. Instead #include "counter.h" and link the .cpp file to your executable.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
  • I also did what you suggested and moved my counter.cpp file to the footer of the counter.h file. Thanks that is a bit cleaner. – Tim Herbert Feb 21 '18 at 01:26