0

So i have a homework where i need to create a student class (the alumno class) with a name and 3 grades, and a method that calculates the final grade, and where i have a problem is that i need to append both the final grade and the name to two vectors respectively, those vectors are the attributes of the class LibroDeClases. The after the end of the function the contents appended to those vectors dissapear, i can see in the vs debugger that they are indeed getting appended, but as i said, they dissapear after the function calcularNota() ends.

I'll leave you the code below:

class libroDeClases {
public:
    vector<string> nombres;
    vector<float> notasDef;
};

class Alumno {
private:
    string nombre;
    float n1, n2, n3;
    float notaDef;

public:
    Alumno(string n, float x, float y, float z) {
        this -> nombre = n;
        n1 = x;
        n2 = y;
        n3 = z;    }
    void calcularNota(libroDeClases L) {
        float nd = (n1 + n2 + n3) / 3;
        notaDef = nd;
        L.notasDef.push_back(nd);
        L.nombres.push_back(nombre);
    }


int main() {
    libroDeClases Libro;
    Alumno a1("Oscar", 4.0, 4.7, 5.5);
    Alumno a2("Tomás", 5.7, 6.5, 7.0);
    Alumno a3("Macarena", 5.3, 5.7, 4.8);
    a1.calcularNota(Libro);
    a2.calcularNota(Libro);
    a3.calcularNota(Libro);

Thank you for your help!

Tomás
  • 17
  • 4
  • 3
    You’re passing the class by value, so you’re modifying a copy – Taekahn Mar 27 '22 at 14:23
  • 1
    Add one & here: "void calcularNota(libroDeClases& L)". Then it will work. – A M Mar 27 '22 at 14:24
  • 1
    `void foo(int x) { x = 10; } int main() { int x = 0; foo(x); // x is still 0, not 10 }` -- Your issue is no different than that code. Unlike other languages you may have used, unless you specify `&` to mean you want a reference passed, all types are passed by value. – PaulMcKenzie Mar 27 '22 at 14:24

0 Answers0