Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ declaring a static object in a class

I'm trying to declare a static object of a class A that I wrote in a different class B, like this:

class A // just an example
{
    int x;
public:
    A(){ x = 4; }
    int getX() { return x; }
};

class B
{
    static A obj1;  // <- Problem happens here
public:
    static void start();
};

int main()
{
    B::start();
}

void B::start()
{
    int x = obj1.getX();
}

What I want to achieve is to get int x in B::start() to equal int x in class A (4).

I tried googling all this for the past hour and all I understood was that C++ doesn't allow static objects' declarations. Is that correct?

If so, here's my question. How can I get the same result? What are my available workarounds? Keeping in mind that the rest of my code depends on the functions in class B to be static.

Error

error LNK2001: unresolved external symbol "private: static class A B::obj1"

Thanks!

like image 938
ThunderStruct Avatar asked Apr 10 '15 01:04

ThunderStruct


People also ask

Can we declare static object?

Note: To create a static member(block, variable, method, nested class), precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.

Can we declare static variable in class?

Static variables in a class: As the variables declared as static are initialized only once as they are allocated space in separate static storage so, the static variables in a class are shared by the objects. There can not be multiple copies of same static variables for different objects.

How do you initialize a static object?

For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value.

What is static declaration in C?

A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.


1 Answers

You should initialize static var, the code:

class A // just an example
{
    int x;
public:
    A(){ x = 4; }
    int getX() { return x; }
};

class B
{
    static A obj1;  // <- Problem happens here
public:
    static void start();
};

A B::obj1; // init static var

int main()
{
    B::start();
}

void B::start()
{
    int x = obj1.getX();
}
like image 147
thinkerou Avatar answered Oct 01 '22 02:10

thinkerou