I have a program that reads lines from a file looking like this:
...
name1 (123)
name2 (345)
...
It then stores each line as an object of MyClass in a map called namelist. The key of namelist is the name of the object the value is the object itself. In the first version of the code namelist was of type map< string,MyClass >, and the objects were created in the loop as MyClass obj; (and ofc all '->' were '.'. But that only created a map of equal objects, why? I've read that you rarely need to use 'new' on objects in c++. Why do i need it here?
ifstream myfile ("input.txt");
map<string,MyClass*> namelist;
string line;
while ( getline(myfile,line) ) {
istringstream iss(line);
string word;
while (iss>>word) {
MyClass* obj = new MyClass;
obj->name = word;
iss>>word;
sscanf(word.c_str(),"(%d)",&obj->number);
namelist.insert( pair<string,MyClass*>(obj->name,obj) );
}
}
myfile.close();