So, I just spent the last 3 or 4 hours fixing a bug in a program of mine. The program would compile, but then immediately crash as soon as it started running, with no explanation. The compiler gave no description of the error, since it compiled. But although I finally fixed the problem, I still don't really understand what was wrong in the first place.
So, the program was a Real Time Strategy game Ive been working on. It has a class called unit, which represents individual units on the battlefield, and another class unitType, which stores unchanging stats and data on different unit types. The nightmare started when I decided to write a new constructor for unitType that would read the data in from a txt file.
Class declaration in header:
The full function in source file:
// lots of data members...
unitType(int id = 0, std::string path =NULL);
// some other functions...
In the Main function I did this:
unitType::unitType(int id, std::string path)
// read in some data...
And, in the declaration of the unit class:
theTypes = unitType(0, "unitData.txt");
The reason for the default arguments to the unitType constructor is that the line where I declare an array of 20 unitTypes would not compile unless there was a constructor that would take zero arguments.
unit(int x, int y, unitType theType);
The code would compile, but instantly crash. I finally fixed it by completely eliminating the "std::string path" argument to the unitType constructor, and just putting "unitData.txt" directly into the ifstream command in the constructor.
My theory is that when I declared the array, the constructor was called with the default argument of NULL, and then ifstream was called with a NULL argument. But the thing is, when I changed ifstream(path) to ifstream("unitData.txt"), it still wouldn't work. Only once I completely removed the std::string path argument from the constructor would it not crash.
I have it fixed now of course, and I really don't need to take in path as an argument, I just did that out of habit I guess. But I was curious exactly what the problem was after the hours I spent fixing it.