Hanumant Mittal
Hanumant Mittal

Reputation: 3

Unable to access static member from static function

I am using the below code snippet.

#include <iostream>
struct Entity
{
    static int x,y;
    
    static void print()
    {
        std::cout << x << " Yoo -- ooY " << y << std::endl;
    }
};
// int Entity::x;
// int Entity::y;
int main() {
    Entity::print();
    return 0;
}

I get a compilation error on trying to run this:

/usr/bin/ld: /home/ItfG3m/ccKGCJ5N.o: in function `main':
prog.cpp:(.text.startup+0xf): undefined reference to `Entity::x'
/usr/bin/ld: prog.cpp:(.text.startup+0x31): undefined reference to `Entity::y'
collect2: error: ld returned 1 exit status

If I uncomment this, it works fine:

// int Entity::x;
// int Entity::y; 

Shouldn't a static method be able to access static variables? Why is a declaration needed?

Upvotes: 0

Views: 1144

Answers (1)

Nyque
Nyque

Reputation: 391

You need to define storage for the static variables:

#include <iostream>

struct Entity
{
    static int x,y; // <-- declares that variables exist somewhere
    
    static void print()
    {
        std::cout << x << " Yoo -- ooY " << y << std::endl;
    }
};

int Entity::x = 0; // <-- defines storage
int Entity::y = 0; // <-- defines storage

int main() {
    Entity::print();
    return 0;
}

Upvotes: 2

Related Questions