Share via


How to create a global object of a ref class type?

Question

Tuesday, June 3, 2014 5:23 PM

Hi,

In Visual C++ 2013, I am trying to create a global object of a ref class because I need to share the values between various .cpp files.

But I am having an error: "a variable with static storage duration cannot have a ref class type".

Please help me to solve this.

Thanks.

All replies (5)

Tuesday, June 3, 2014 5:36 PM ✅Answered | 2 votes

Make it a static member of a ref class/struct:

// in a header file

ref struct Globals {

    static YourClass ^globalVar = gcnew YourClass;

};

// use it like this:

Console::WriteLine(Globals::globalVar);


Thursday, June 5, 2014 2:10 PM ✅Answered | 1 vote

Should I create the 2nd class in the header file of the 1st class??

Because I tried that and an error came in the console line that the object is undefined.

Classes are not created -- they are defined.

Objects are created, but your class has only static members, so no object is needed.

You should be able to define your class in its own header file or in the header file of another class. Just make sure that you include this header everywhere the class is used.

David Wilkinson | Visual C++ MVP


Wednesday, June 4, 2014 11:52 AM

But then if I make it a static member of another class, then finally I will need to make global object of the 2nd class in order to access the 1st class object.

& Situation will be the same like above explained, I think.


Wednesday, June 4, 2014 12:17 PM

Erm, no. That's why I said to make it a static member, so you don't need an object of type Globals.


Thursday, June 5, 2014 1:46 PM

Should I create the 2nd class in the header file of the 1st class??

Because I tried that and an error came in the console line that the object is undefined.