Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing static class variables in C++?

Tags:

c++

class

static

Duplicate:
C++: undefined reference to static class member

If I have a class/struct like this

// header file class Foo {    public:    static int bar;    int baz;    int adder(); };  // implementation int Foo::adder() {    return baz + bar; } 

This doesn't work. I get an "undefined reference to `Foo::bar'" error. How do I access static class variables in C++?

like image 829
Paul Wicks Avatar asked Apr 13 '09 06:04

Paul Wicks


People also ask

How do you access static class variables?

A static member variable: • Belongs to the whole class, and there is only one of it, regardless of the number of objects. Must be defined and initialized outside of any function, like a global variable. It can be accessed by any member function of the class. Normally, it is accessed with the class scope operator.

How do I access static data members?

We can access the static member function using the class name or class' objects. If the static member function accesses any non-static data member or non-static member function, it throws an error. Here, the class_name is the name of the class. function_name: The function name is the name of the static member function.

Where do static variables go in C?

The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).

Can static member accessed through the class object?

The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.


2 Answers

You must add the following line in the implementation file:

int Foo::bar = you_initial_value_here; 

This is required so the compiler has a place for the static variable.

like image 84
Drakosha Avatar answered Sep 19 '22 00:09

Drakosha


It's the correct syntax, however, Foo::bar must be defined separately, outside of the header. In one of your .cpp files, say this:

int Foo::bar = 0;  // or whatever value you want 
like image 24
Chris Jester-Young Avatar answered Sep 21 '22 00:09

Chris Jester-Young