Home > OS >  C std::string attribute of a class comes up as an empty string after initialized
C std::string attribute of a class comes up as an empty string after initialized

Time:03-27

So i have a pretty straight foward homework that consist in creating a student class that has a name and 3 grades as attributes and a method to caluculate the final grade and append the name as long as the final grade to 2 vectors respectively, the problem comes up when i try to append the name to the vector as its appended as an empty string, but the debugger shows the instance of that student class (the "Alumno" class) has actually a name.

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 nombre, float x, float y, float z) {
        nombre = nombre;
        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);
    a1.calcularNota(Libro);

thank you for your help!

Edit: i added the "Libro" class in order to make the code compile, i forgot to provide it sorry about that.

CodePudding user response:

As the user Taekahn said in a comment, i used This -> and it now appends it perfectly.

Thank you.

CodePudding user response:

If you pass the object by reference to calcularNota then the string gets printed successfully. If you just pass by value, a copy of the object gets made but doesn't change the value of the original object: https://godbolt.org/z/fGzWvzW1b

  • Related