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
nextIdandcountas static data members. - Write a static member function to set the first ID, and one to read the count.
- Give
Studentconst 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
101 3 Asha Bilal Chen
101 Asha 102 Bilal 103 Chen students 3 next id 104
1 1 Solo
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;
}