Computernerd
Computernerd

Reputation: 7766

Undefined reference to static variable and static method

#include <iostream>
using namespace std;

class Assn2
{
  public:
     static void set_numberofshape();
     static void increase_numberofshape();

  private:         
      static int numberofshape22;
};

void Assn2::increase_numberofshape()
{
  numberofshape22++;
}

void Assn2::set_numberofshape()
{
  numberofshape22=0;
} // there is a problem with my static function declaration

int main()
{
  Assn2::set_numberofshape();
}

Why do I get an error undefined reference to Assn2::numberofshape22 when I compile this?

I am trying to declare an static integer :numberofshape22 and two methods.

Method 1 increase numberofshapes22 by 1

Method 2 initialise numberofshape22 to 0

What am I doing wrong ??

Upvotes: 1

Views: 5674

Answers (2)

Pierre Fourgeaud
Pierre Fourgeaud

Reputation: 14510

The declaration of a static data member in the member list of a class is not a definition.

To respect the one Definition Rule you must define a static data member. In your case you only declared it.

Example:

// in assn2.h
class Assn2
{
  // ...
  private:         
      static int numberofshape22; // declaration
};

// in assn2.cpp

int Assn2::numberofshape22; // Definition

Upvotes: 2

harper
harper

Reputation: 13690

You just declared the variable. You need to define it:

int Assn2::numberofshape22;

Upvotes: 4

Related Questions