Q.Write a program that shows a class called gamma that keeps
track of how many objects of itself there are. Each gamma object
has its own identification called ID. The ID number is set equal to
total of current gamma objects when an object is created.
Test you class by using the main function below.
int main()
{
gamma g1;
gamma::showtotal();
gamma g2, g3;
gamma::showtotal();
g1.showid();
g2.showid();
g3.showid();
cout << "----------end of program----------\n";
return 0;
}
Runtime output
Total is 1
Total is 3
ID number is 1
ID number is 2
ID number is 3
----------end of program----------
Destroying ID number 3
Destroying ID number 2
Destroying ID number 1
C++ please
#include <iostream>
using namespace std;
//Idea is to use static variable to keep track
//of number of classes
class gamma
{
// This is to store ID
int ID;
//This is to keep track of total number
//objects of the gamma class
static int objCount;
public:
//Constructor
gamma()
{
//Pre increment objCount and store in ID
ID = ++objCount;
}
//Destructor
~gamma()
{
cout<<"Destroying ID number"<<ID<<"\n";
//Pre decrementing objCount as one object is deleted
--objCount;
}
void showid()
{
cout << "ID number is:" << ID << "\n";
}
static void showtotal(void)
{
cout << "Total is:" << objCount<< "\n";
}
};
//Initializing the stact variable.
//Static variables are set to 0(by default).
int gamma::objCount;
int main()
{
gamma g1;
gamma::showtotal();
gamma g2, g3;
gamma::showtotal();
g1.showid();
g2.showid();
g3.showid();
cout << "----------end of program----------\n";
return 0;
}
Output Screenshot:
(Note: Please refer to the screenshots of the code to understand the indentation of the code)
Code Screenshots:
gamma class:
main():
Get Answers For Free
Most questions answered within 1 hours.