1

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);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Dinnea
  • 13
  • 6
  • Pop quiz: those pointers in the vector -- are they pointers to constant or non-constant objects, and are you passing a reference to a constant or a non-constant object to this function? – Sam Varshavchik Oct 26 '21 at 20:43
  • Minor quibble: Your function is called `addModules()` (emphasis on plurality), but you can only ever add a single module at a time. – sweenish Oct 26 '21 at 20:43
  • Bad Rule of 0/3/5 in `StudyModule`. It should be Rule of 0, but 2 of the (not) required functions are declared. `const` private members are pointless. – sweenish Oct 26 '21 at 20:45

1 Answers1

1

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Yes, thank you, that fixed it all :D such as small detail breaking everything like usual :) – Dinnea Oct 26 '21 at 20:52