Jump to content
  • Advertisement
Sign in to follow this  
obi-wan shinobi

[.net] arrays of ref class objects

This topic is 4867 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to create an array of managed objects in c++ and assign something to the object once created. Because the array declaration apparently doesn't allow you to use anything but the default constructor, overloading the constructor seems to be out of the question. Anyway, take the code below:
ref class refc {
  private:  int i,j;
  public:  
    void disp() { Console::Write("disp() called.\n"); }
    void assign(int a, int b) { i = a;  j = b; }
};

int main() {
  array<refc^> ^r = gcnew array<refc^>(2);
  r[0]->disp();        //works fine
  r[1]->assign(1,2);   //crashes the program
}

The problem is that the call to the 'assign' method triggers a NullReferenceException. I guess that somehow, arrays of managed classes (and not unmanaged classes) have a problem with assigning values to variables during method calls. Otherwise, the program will run fine. As of yet, I haven't tested using lists or collections because I haven't learned much on them yet. So, why does the code above result in a NullReferenceException?

Share this post


Link to post
Share on other sites
Advertisement
Your gcnew call will allocate an array of null references of type refc. You need to allocate your refc objects separately:


array<refc^>^ r = gcnew array<refc^>(2);
for (int i = 0; i < 2; i++)
r = gcnew refc();




And as for why disp() succeeds while assign() fails, disp() does not need a non-null this reference, while assign() needs one. This should make it clearer:


ref class refc {
...
void disp() {
// does not need this
Console::Write("disp() called.\n");
}
void assign(int a, int b) {
this->i = a; // needs this != nullptr
this->j = b;
}
};

Share this post


Link to post
Share on other sites
Thans for the help. I wasn't aware that the array keyword only makes null references. The documentation doesn't mention it from what I looked at under arrays. I suppose I'll eventually know how arrays of objects work under .net compared to native c++...

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!