user14416
user14416

Reputation: 3032

Change Static Variable Scope

I have in one C++ class a definition of static variable:

static SomeType MyClass::StaticVariable;

In another class I want to use this variable without MyClass prefix. Can I do that? How?

Upvotes: 0

Views: 77

Answers (2)

Greg Hewgill
Greg Hewgill

Reputation: 994649

You could use a reference:

class MyOtherClass {
    static SomeType &StaticVariable = MyClass::StaticVariable;
    // ...
}

You will have to ensure that you don't try to reference MyOtherClass::StaticVariable before MyClass::StaticVariable has been constructed (at program startup).

Upvotes: 1

user405725
user405725

Reputation:

You can do that only if that "another class" is derived from MyClass and StaticVariable has either public or protected visibility. Alternatively, you can move that member variable to some other scope or declare a reference/pointer and point it to that variable so that later you have to do less typing.

Upvotes: 0

Related Questions