Everlit
Everlit

Reputation: 27

Class array with multiple types? How to access one type in the array?

Here's a small portion of my code:

class Student
{
    private:
        string ID, fname, lname, level;
        double gpa;
}

So let's say that I make an array a[] of type Student, is there a way to access just the double 'gpa' of each array element? Not exactly sure how to do this. Any help would be appreciated. I need to learn how to google better because I feel like this shouldn't be too hard to look up but I still couldn't find what I was looking for.

Upvotes: 0

Views: 50

Answers (2)

Andria
Andria

Reputation: 5065

I see CoryKramer showed you how to do it with a std::array but if you just want to use a normal array, here is what you should do:

#include <cstdio>
#include <string>

class Student
{
public:
  double get_gpa() {return gpa;}
  void set_gpa(double _gpa) {gpa=_gpa;}
private:
  std::string ID, fname, lname, level;
  double gpa;
};

int main() {
  Student a[30];
  //Initialize
  for(int i = 0; i < 30; i++) {
    a[i].set_gpa((double)i/7.5);
  }
  //Print out
  for(int i = 0; i < 30; i++) {
    printf("a[%i].gpa = %f\n",a[i].get_gpa());
  }
}

Essentially you just do Student a[30]; to create thirty students in an array, then you can initialize their values to be different with a for loop or input from a "Teacher". Lastly you can print them using another for loop later like so: printf("%f\n",a[i].get_gpa()); or with std::cout it would be `

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

If you have an array

std::array<Student, 10> students;

You could say

for (auto const& student : students)
{
    std::cout << student.gpa << " ";
}

You can obviously do this for an arbitrary element as well

students[i].gpa = 4.0;

Of course you have to make sure you have public methods to access these members if they are specified private

class Student
{
public
    Student() = default;
    Student(double _gpa) : gpa(_gpa) {}

    double get_gpa() const { return gpa; }
    void set_gpa(double _gpa) { gpa = _gpa; }

private:
    double gpa = 0.0;
}

Then

students[i].set_gpa(4.0);

Upvotes: 3

Related Questions