System.nullreferenceexception vc++

AyashiKaibutsu

Diamond Member
Jan 24, 2004
9,306
4
81
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;
//}
}
};
 

iCyborg

Golden Member
Aug 8, 2008
1,353
62
91
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.
 

AyashiKaibutsu

Diamond Member
Jan 24, 2004
9,306
4
81
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 : ).
 

hans007

Lifer
Feb 1, 2000
20,212
18
81
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.