Suppose I create a CountedValue<int> object. Then my counter of objects in exist
ID: 3908560 • Letter: S
Question
Suppose I create a CountedValue<int> object.
Then my counter of objects in existence is now at 1.
Now, supposed I create another CountedValue<int> object.
Then my counter goes up one more to 2.
Then "somehow", one of the objects memory is deallocated. In other words, the object is "destroyed".
My Counter would drop down to 1, since there is now only 1 object in existence.
****There is a caveat to the CountedValue Template Class which is that the static variables are bound to the specific datatype you use with the template. So if I create 2 ints and 2 doubles using the Template, my count is not at 4. There would be two separate counts, one for CountedValue<int> and another for CountedValue<double>.
1 #include «iostream» 2 template int F> class Die 4 5 6 public Die() int roll); static void randomize (int seed0) unsigned int getFaces) private unsigned int _faces 12 13 templatecint F> 14 Die: :Die() 15 16 17 18 19 20 template 21 int Die roll() :_faces (F) return rand() %-faces; 23 24 25 template 26 27 28 29 30 31 32 srand (time (NULL)); unsigned int Die: :getFaces ) return_faces; int main() std::coutExplanation / Answer
The question says "Add another static variable to CountedValue class..." But you have provided the Die class. I guess you have another class named CountedValue. Since it is not provided, I have created one with just the description in the question. You may want to copy the new code as additions into your existing code.
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class CountedValue
{
private:
static int counter;
public:
CountedValue() //constructor
{
counter++;
}
static int getCounter() //function to return the value of counter
{
return counter;
}
~CountedValue()//destructor
{
--counter;
}
};
//initialize the static class variable outside
template <typename T>
int CountedValue<T>::counter = 0;
int main()
{
CountedValue<int> intObj1, intObj2;
cout << "created 2 objects of CountedValue<int> type" << endl;
cout << "CountedValue<int>::counter = " << (CountedValue<int>::getCounter()) << endl << endl;
CountedValue<double> doubleObj1, doubleObj2, doubleObj3;
cout << "created 3 objects of CountedValue<double> type" << endl;
cout << "CountedValue<double>::counter = " << (CountedValue <double>::getCounter()) << endl << endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.