Question

How do I access a member of a static member of other class?

Like so:

code.hpp:

class A
{
public:
    int* member;
    A();
};

class B
{
public:
    static A* StatOBJ;
};

code.cpp:

A* B::StatOBJ = new A();
int* B::StatOBJ->member = 42                //ERROR

I would prefer to have this outside of main() (or any other function - just like static variables are defined) but I tried it inside main() as well.

A() puts some value to member (and therefore initializes it) and I want to change it.

When I try to compile this I get:

error: expected initializer before '->' token

on the line with //ERROR

Was it helpful?

Solution

A::member is not declared as static, so do not specify its data type again when assigning its value:

B::StatObJ->member = ...;

Also, A::member is declared as a pointer, so you have to allocate it before you can assign a value to it:

B::StatObJ->member = new int;
*(B::StatObJ->member) = 42;

Or:

B::StatObJ->member = new int(42);

Either way, both of those would be better served by giving A a constructor to handle that allocation/assignment:

class A
{
public:
    int* member;
    A();
    ~A();
};

A::A()

    : member(new int(42))
{
}

A::~A()
{
    delete member;
}

A* B::StatObJ = new A();

Or better:

class A
{
public:
    int* member;
    A(int value);
    ~A();
};

A::A(int value)
    : member(new int(value))
{
}

A::~A()
{
    delete member;
}

A* B::StatObJ = new A(42);

OTHER TIPS

Some minor modifications to your code:

#include <iostream>

class A
{
    public: //needs to be public
     int* member;
};

class B
{
    public: // needs to be public
    static A* StatOBJ;
};
A* B::StatOBJ; //needs to be "defined" not just "declared"



int main(){
     B::StatOBJ = new A(); // you dont want to allocate more memory so drop the type
     B::StatOBJ->member = new int(42);   // unless you change A::member to int instead of (*int) this must be done  
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top