I've got the bare shell of a program with a "BasicObject" class and a randum number generator class implemented. When I run the program, the console closes immediately, and cin functions, system("pause"), etc. have no effect. I suspect a crash, but can't find what the source might be. Any help?
BaseObject.cpp:
#include "BaseObject.h"
#include "RandNumGenerator.h"
#include <iostream>
#include <string>
using namespace std;
BaseObject::BaseObject() {
RandNumGenerator* numGen;
set_id(numGen->generate_randNum_str(5));
delete numGen;
}
BaseObject::~BaseObject() {}
...
//void - sets value of string "id"
void BaseObject::set_id(string newId) {
id = newId;
}
Here's the main function:
#include <iostream>
#include <string>
#include "BaseObject.h"
using namespace std;
int main() {
string userIn = "";
BaseObject* obj;
while (userIn != "q") {
cout << "Id of \"obj\" is " << obj->get_id() << endl;
cout << endl << "Type 'q' to quit." << endl;
cin >> userIn;
}
return 0;
}
It's crashing, because here
obj->get_id()
obj is not initializated yet. Just a pointer to memory with some random garbage.
You need something like
BaseObject* obj = new BaseObject()
Before you can use obj