Can I reference a non static member to a private string array in a class? C++

100 Views Asked by At

I'm trying to have three private data members (string firstName[], string lastName[], and float testScores[]) in a class where the number of elements is an input from a public data member, totalStudents (which is user defined). Further, adding const in front of totalStudents isn't an option because the value changes when the user inputs the value. Here is the header code (C++):

#ifndef __newClassHeader.h__
#define __newClassHeader.h__
#include <iostream>
#include <string>
using namespace std;

class student {
    public:
        student();
        int totalStudents;
        int askStud() {
            cout << "Enter the number of students: ";
            cin >> totalStudents;
        }
        

    private:
        string FirstName[totalStudents]; // error: a nonstatic member reference must be relative to a specific object
        string lastName[totalStudents];  // error: a nonstatic member reference must be relative to a specific object
};

#endif

I tried adding a totalStudentsPtr variable (that points to totalStudents) after the user info, but that spit out the same issue. For example, I tried this

#ifndef __newClassHeader.h__
#define __newClassHeader.h__
#include <iostream>
#include <string>
using namespace std;

class student {
    public:
        student();
        int totalStudents;
        int askStud() {
            cout << "Enter the number of students: ";
            cin >> totalStudents;
        }
        string firstName[totalStudents]; // error– a nonstatic member reference must be relative to a specific object
        string LastName[totalStudents];  // error– a nonstatic member reference must be relative to a specific object
        

    private:
        string* FirstName;
        string* lastName;
};

#endif

but it gives the same error code. Also, I tried using protected instead of private, but that also didn't work.

1

There are 1 best solutions below

3
On

When you declare an array field as string firstName[totalStudents]; you are telling the compiler to allocate static (read stack) memory for an array with a number of elements that is not yet known (also dynamic). This is not how the compiler works.

You need to either use a value that is constant at compile time, or use std::vector:

class student {
    
    public:
        student();
        int askStud() {
            cout << "Enter the number of students: ";
            cin >> totalStudents;
        }
        

    private:
        vector<string> FirstName; // Dynamically sized!
        vector<string> lastName;  // Dynamically sized!
};

P.S. Try to avoid using using namespace std; in header files as it pollutes the global namespace.