Question 2 6 points Suppose we had a class called Person and

Question 2 [6 points]

Suppose we had a class called Person, and in our program we wanted to keep track of the total number of people. Every time we create a Person, we want to increment the total population by one, and every time we destroy a Person, we want to decrement the total population by one. However, we want to achieve this without using global variables. Given the following implementation of the class Person, please indicate whether using the static qualifier works for our case or not and also write what the main function outputs.

class Person {

private:

    string name;

public:

    static int population;

    Person() {

        ++population;

        name = \"Person \" + to_string(population);

    }

    Person(string val) {

        name = val;

    }

    ~Person() {

      --population;

    }

    string get_name() {

        return name;

    }

};

int Person::population = 0;         // initializes the population to 0

int main(void) {

    Person pers1;

    Person pers2(\"Hello\");

    cout << Person::population << endl;

    cout << pers1.get_name() << endl;

    cout << pers2.get_name() << endl;

}

Is this a valid implementation? Why or why not?

What does the function output?

Solution

This is a valid implementation.

Satic member will be intialized only once.

Output

2 // cout << Person::population << endl;

Person1 // cout << pers1.get_name() << endl; Since value is not given in constructor

Hello // cout << pers2.get_name() << endl; Since we gave Hello as argument in the constructor

After this the value of population will be deleted when both destructor of both objects are called.

Question 2 [6 points] Suppose we had a class called Person, and in our program we wanted to keep track of the total number of people. Every time we create a Per
Question 2 [6 points] Suppose we had a class called Person, and in our program we wanted to keep track of the total number of people. Every time we create a Per

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site