Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Add another static variable to the counted value class (CountedValue) that is al

ID: 3908896 • Letter: A

Question

Add another static variable to the counted value class (CountedValue) that is always equal to the number of counted values in existence in the program. Recall that destructors are called when an object is deleted for any reason. Give the class a member function so that the value of this variable may be obtained. and more explaination :

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>.

#include cvi(5); Countedvalue cvd (4.1); 35

Explanation / Answer


Given below is the fixed/completed code for the question.
Please do rate the answer if it was helpful. Thank you


#include <iostream>
using namespace std;
template <class V>
class Countedvalue
{
public:
Countedvalue(V x):_order(c++),_value(x)
{
++numObjects;
}

Countedvalue(const Countedvalue& count)
{
_order = c++;
_value = count._value;
++numObjects;
}

Countedvalue& operator=(const Countedvalue& count)
{
if(this != &count)
{
_value = count._value;
}
return *this;
}

V getvalue() const
{
return _value;
}

void setvalue(V v)
{
_value = v;
}

int getorder() const
{
return _order;

}
static int getNumObjects()
{
return numObjects;
}
~Countedvalue()
{
--numObjects;
}
private:
V _value;
int _order;
static int c;
static int numObjects;
};

template<class V>
int Countedvalue<V>::c = 0;

template<class V>
int Countedvalue<V>::numObjects = 0;

int main()
{
Countedvalue<int> cvi_1(5), cvi_2(9);
Countedvalue<double> cvd_1(2.3), cvd_2(4.3), cvd_3(5.6);

cout << "No. of int Countedval objects= " << Countedvalue<int>::getNumObjects() << endl;
cout << "No. of double Countedval objects = " << Countedvalue<double>::getNumObjects() << endl;


}


output
=====
No. of int Countedval = 2
No. of double Countedval = 3

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote