Joshua
Joshua

Reputation: 4320

Undefined reference to a static member of the class

I am working on a homework assignment, and I have almost everything done except for this obnoxious static value that our professor wishes us to use: value

The header file contains:

private:
    static int value;

And we have to have a function calculate the value, like so:

static void calculate()
{
    long a = 1L;
    int count = 0;

    while( a != 0 )
    {
        a = a << 1;
        count++;
    }

    value = count;
}

This is essentially calculating the number of bits in a long, using bit shifting.

However, I am getting the error " undefined reference to `Class1::value'

I've spent the last hour and a half figuring this out, and it's killing me. Any help would be great, all searches have come up dead.

Thanks!


Update:

I included

int Class1::value = 0;

However, now I am getting an error saying "error: int Class1::value is private

Upvotes: 2

Views: 1032

Answers (2)

Roman Byshko
Roman Byshko

Reputation: 9042

In your *.cpp file add

int ClassName::value = 0;

This will allocate storage for a value.

The piece of code that you actually have in a class declaration just declares this variable (makes the compiler aware that such a variable exists). However, each variable must be declared and defined. A definition will make sure the storage is put aside for this variable and create a symbol your compiler was unable to find before.

Upvotes: 4

KV Prajapati
KV Prajapati

Reputation: 94653

You need to define a static data member in (.cpp) source file with following syntax:

datatype Your_ClassName::variable;

Upvotes: 0

Related Questions