I am doing an assignment for a C++ class and I am getting an error when using push back with vector. I honestly cannot find any info on why this isnt working and giving me a "no instance of overloaded function" error
class StudentData {
class StudyModule {
private:
const int studyModuleCode;
const std::string studyModuleName;
public:
StudyModule();
StudyModule(const StudyModule& copy);
~StudyModule();
};
private:
const int studentNumber;
std::string studentName;
std::vector<StudyModule*> modules;
public:
StudentData();
StudentData(const StudentData& copy);
~StudentData();
void addModules(const StudyModule& module);
int howManyModules();
};
void StudentData::addModules(const StudyModule& module)
{
this->modules.push_back(&module);
}
The function addModules()
is declared like this:
void addModules(const StudyModule& module);
that is, its parameter is a reference to const
object.
But the vector has a pointer to a non-const object as its template argument:
std::vector<StudyModule*> modules;
Thus, the compiler issues a message for this statement:
this->modules.push_back(&module);
because the expression &module
has the type const StudyModule *
, ie a pointer to a const object.
Even if you would change the template argument of the vector like this:
std::vector<const StudyModule *> modules;
your approach will be unsafe, because the user can pass a temporary object of type StudyModule
to the function. In this case, storing a pointer to this object in the vector will become invalid when the temporary object is destroyed afterwards.