3. In the program, countobjects.cpp a static member is used to keep track of the
number of objects existing at all times.
1. Run the program and capture the output to show that the program doesn’t do
what is intended. Note that you cannot use system(“pause”); statement to
pause execution as this prevents you from seeing the destructions which take
place at the end of the program. Instead, run the program using a command
line window.
2. How can the class be fixed? Note that it is the class which must be fixed and
not the main program or the function call.
3. Fix the class and show that your new class works.
/* File: countobjects.cpp
A class that keeps track of the number of objects created and
destroyed
using a static member*/
#include
using namespace std;
class myclass
{
private:
int data; // data value stored in the
object
static int number_of_objects; // current number of objects
public:
myclass(int init=0); // constructor, increments
object_count
~myclass(void); // destructor, decrements
object_count
};
/* the modifier, static, when used with a class member means that
there
is only one instance of that member which is shared by all
objects.
For a non-static data member, each object has its own instance of
the
member.
We can refer to static data members even when we don’t have any
objects
at hand. In fact this is how we intialize a static member rather
than
using the constructor. */
int myclass::number_of_objects = 0; // initialize to zero
// call by value function
void f(myclass x);
int main()
{
myclass x(1);
f(x);
5
cout
return 0;
}
myclass::myclass(int init)
{
data = init; // initialize data
number_of_objects++; // increment the number of objects
// print a little message
cout
cout
}
myclass::~myclass(void)
{
number_of_objects–; // decrement the number of objects
// print a little message
cout
cout
}
void f(myclass x)
{
cout
}



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *