Hello all, I am trying to create a vector of object Course and then fill the vector with a temp value. A loop will cycle through entries that come from a text file to create the temp values. My issue is with the snippet below, but I have included the entire program so far. Yes, there are other things commented out, but I am trying to make sure that separate parts are working before combined. The following loop yields the forthcoming errors.
while (getline(inStream, lines)){
cout << lines << endl;
Course *temp = new Course(lines);
Course.push_back(temp);
}
main.cpp: In function 'int main()':
main.cpp:21:11: error: 'temp' was not declared in this scope
Course *temp = new Course(lines);
^~~~
main.cpp:21:22: error: expected type-specifier before 'Course'
Course *temp = new Course(lines);
^~~~~~
You have a vector named Course, and a class named Course. This is causing you trouble. Don't name variables the same as classes.
Also, you made a vector of Course objects, and then you tried to push_back onto it a pointer-to-Course. You can't do that. If you make a vector of Course objects, you may only put Course objects into that vector.
Also, don't use new. Don't use new. DON'T USE NEW.
At first I didn't use a pointer. I tried using a temporary variable to hold the value of the class object that I wanted to push_back to the vector, but that also produced an error.
error message
1 2 3 4
main.cpp: In function 'int main()':
main.cpp:23:34: error: no match for call to '(Course) (std::__cxx11::string&)'
thisCourse.push_back(temp(lines));
^
Objects are constructed when they are defined. It's too late to say temp(lines) on line 22 and expect the constructor to run.
Instead, create an unnamed temporary Course object, as in thisCourse.push_back(Course(lines));
or let the standard library do the exact same thing for you with emplace_back, as in thisCourse.emplace_back(lines);.
Your naming leaves some things to be desired. thisCourse is actually a collection of courses; lines is actually just one line.
Course temp; - this creates a Course object, named temp, using the default constructor. Course temp(lines); - this creates a Course object, named temp, using the constructor that accepts a single parameter of type string. temp(lines) - this appears to be an attempt to call a function (that doesn't exist) named temp, that accepts a single parameter of type string.