C++: Student IDs from a static counter

Give every new object the next number, using data that belongs to the whole class.

What to build

A Student class that gives each new student the next ID from a shared counter.

Requirements

  • Keep nextId and count as static data members.
  • Write a static member function to set the first ID, and one to read the count.
  • Give Student const getters for its ID and name.
  • Print each student, then the count and the next ID that would be given out.

Input

The first line has the first ID. The second line has n. The third line has the n names.

Output

n lines ID NAME, then students N, then next id X.

Constraints

1 ≤ n ≤ 100, and the first ID is from 0 to 100000.

Example

Input:

101
3
Asha Bilal Chen

Output:

101 Asha
102 Bilal
103 Chen
students 3
next id 104

Why it works

A static member exists once for the whole class, so every constructor reads and updates the same counter. That is what makes the IDs unique and in order.

Examples

Example 1 · Input
101
3
Asha Bilal Chen
Expected output
101 Asha
102 Bilal
103 Chen
students 3
next id 104
Example 2 · Input
1
1
Solo
Expected output
1 Solo
students 1
next id 2

Hints

Hint 1

`static int nextId;` belongs to the class. Each constructor takes the current value and then adds 1.

Hint 2

A static member function such as `setStart(int)` can change `nextId` before any student exists.

Hint 3

Define each static data member once, outside the class.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Student {
    static int nextId;
    static int count;
    int id;
    string name;
public:
    Student(string n) : id(nextId), name(n) {
        nextId++;
        count++;
    }
    static void setStart(int first) { nextId = first; }
    static int howMany() { return count; }
    static int peekNext() { return nextId; }
    int getId() const { return id; }
    string getName() const { return name; }
};

int Student::nextId = 1;
int Student::count = 0;

int main() {
    int start, n;
    cin >> start >> n;
    Student::setStart(start);
    vector<Student> list;
    for (int i = 0; i < n; i++) {
        string name;
        cin >> name;
        list.push_back(Student(name));
    }
    for (const Student& s : list) cout << s.getId() << " " << s.getName() << endl;
    cout << "students " << Student::howMany() << endl;
    cout << "next id " << Student::peekNext() << endl;
    return 0;
}

Lesson: Static and const members →