• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

System.nullreferenceexception vc++

AyashiKaibutsu

Diamond Member
So I'm mucking around with c++ at work since I'm bored and just got vc++ installed on my machine. I'm trying to make a board for a game as practice. It compiles and when run throws System.Nullreferenceexception on line 37 of table.h line 5 of main.cpp. I know this is probably stupid, but I've never been good with c++ and just messing around to learn.

#include "Table.h"
int main()
{
Table *theTable = new Table;
theTable->consoleOutput();
return 1;
}

#include <iostream>
using namespace std;
class Table {

private:
signed short int * theTable;
unsigned short int dimensionX;
unsigned short int dimensionY;
unsigned int size;

public:
Table (int x, int y) {
theTable = new signed short int[x*y];
dimensionX = x;
dimensionY = y;
size = x*y;
emptyTable();
}
Table (int size) {
Table (size, size);
}
Table () {
Table (3,3);
}
~Table() {
delete theTable;
}

void emptyTable() {
for (unsigned int a=0; a<size; a++) {
theTable[a] = 0;
}
}
void consoleOutput() {
//for (unsigned short int i=0; i<dimensionX; i++) {
// for (unsigned short int j=0; j<dimensionY; j++){
theTable[0 /*j+i*dimensionX*/] = 1;
// }
// cout<<endl;
//}
}
};
 
Your default constructor constructs a local temporary object with Table(3,3) that is deleted right away - it effectively does nothing so you're calling a method on an uninitialized object. Use default arguments, like Table (int x=3, int y=3), or define a private function init() which would be called by both constructors.
 
Thanks, made a separate function init for it, and it works. Guess calling a constructor from a constructor wasn't a bright move on my part (messing around with stuff to figure little things out is the main point of what I'm doing though : ).
 
I think you might be able to do it in the initialization list.

something like

Table():Table(3,3){}

as well.

I am not 100% sure on this though.
 
Back
Top