How to initialize an array of user-defined objects with a static ID counter?

Viewed 72

Here is my code

#include <iostream>
#include <string>

class Person {
    private:
        int pancakesEaten, personID;
    public:
        Person() {
            pancakesEaten = 0;
            personID = setID();
        }

        static int setID() {
            static int currID;
            return currID++; // Returns currID and then increments.
        }

        bool operator>=(const Person& p);
        bool operator<=(const Person& p);
        void askPancakesEaten();
        void print();
};

bool Person::operator>=(const Person& p) {
    if(this->pancakesEaten >= p.pancakesEaten) {
        return true;
    }
    return false;
}

bool Person::operator<=(const Person& p) {
    if(this->pancakesEaten <= p.pancakesEaten) {
        return true;
    }
    return false;   
}

void Person::askPancakesEaten() {
    std::cout << "Please enter how many pancakes you ate: ";
    std::cin >> this->pancakesEaten;
}

void Person::print() {
    std::cout << this->personID;
    std::cout << "Person " << this->personID << " ate " << this->pancakesEaten << " pancakes"; 
}

int main() {
    Person people[10];
    for(int i = 0; i<10; i++) {
        Person currPerson;
        currPerson.askPancakesEaten();
        currPerson.print();
    }
}

My problem is that I am trying to initialize an array for 10 Person objects, and because of my static method, it is making my static count start at 10 when I enter my for loop.
I know I could get around this easily by just changing my constructor and getting rid of setID and just using i instead, but I am curious if there is another way around it?

1 Answers

... but I am curious if there is another way around it.

Why are you initializing an array and don't use it in the loop then?

for(int i = 0; i<10; i++) {
    people[i].askPancakesEaten();
    people[i].print();
}

Besides that setID() is named a bit unfortunate confusing (getNextID() might be a better, clearer choice IMO), there's nothing wrong with that implementation as you have it.

Also it would be better to make this function private, since how those ID's are kept and managed to be unique for the class instances, is an implementation detail, which should't be publicly accessible.

Related