0

How do I create an array of a grade class variable. I don't understand how to initialize and what to write in main(). from this, is there a way to make a constant? And do I need a for loop to read and output the array? Thanks

class First
{
  public:
    int getId();
    void setId(int);
    int getExam();
    void setExam(int);
    void print();
    First(int studentId, int exam);

  private:
    int id;
    int grade;
};

int main()
{
  int studentId = 0;
  int exam = 0;

  First Student(studentId, exam);

  cout << "Enter student id" << endl;
  cin >> studentId;
  Student.setId(studentId);

  cout << "enter grade" << endl;
  cin >> exam;
  Student.setExam(exam);

  Student.print();

  return 0;

}
1
  • 1
    You declare an array as a class member variable the same way you declare an array anywhere else, such as a local or global variable. Commented May 22, 2013 at 23:19

1 Answer 1

3

If you know the size of the array at compile-time, this is how you would create the array:

First student_list[size];

Though it's more ideal to use compile-time classes like std::array<T, N>:

#include <array>

std::array<int, size> student_list;

If you don't know the size at compile-time, or your compiler doesn't support std::array, use std::vector<T>:

#include <vector>

std::vector<int> student_list;

Moreover, your parameterized constructor (First(int, int)) overrides the default and copy-constructor that the compiler normally provides. Your default constructor can look like this:

First() { }

Otherwise you can use the default specifier with C++11:

First() = default;

However, by using default parameters for your specialized constructor, it can act as a default constructor when given 0 arguments. The following is a good alternative:

First(int studentid = 0, int exam = 0)
{ }

And lastly, yes, you would need some sort of loop to print out each element's grade in succession.

Sign up to request clarification or add additional context in comments.

3 Comments

Also: Need a default constructor, and possibly a copy constructor.
@user1787000 As Keith said, you will also need to implement a default constructor and a copy constructor, otherwise when you create the array you will get errors because it default constructs each element.
+1, but I really disagree with the default arguments for the constructor. It is now also a implicitly converting constructor, which is really unfortunate. I'd rather write a default constructor and delegate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.