In: Computer Science
Create a C++ class with a static member item so that whenever a new object is created, the total number of objects of the class can be reported.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need ANYTHING to change. If you are satisfied with the solution, please rate the answer. Thanks
Note: If you want how many objects are created from within constructor (ie when an object is created, without explicitly invoking the getObjects() method from outside.), let me know.
#include<iostream>
using namespace std;
//a class representing one Student
class Student{
//attribute for storing Student's name
string name;
public:
//static variable storing number of objects created
static int objects;
//constructor taking student name
Student(string nm){
//assigning name
name=nm;
//incrementing number of objects created
objects++;
}
//you can create a destructor here if you want that will decrement objects by 1
//in that way, you can find out the number of active objects (under scope), right
//now, I'm just leaving it upto you.
//returns the name
string getName(){
return name;
}
//static method to return the number of objects created
static int getObjectsCreated(){
return objects;
}
};
//initializing static member variable objects to 0
int Student::objects=0;
//main method for testing
int main(){
//displaying number of objects created initially (should be 0)
cout<<"Number of Student objects created: "<<Student::getObjectsCreated()<<endl;
//creating a Student, now the value must be 1
Student s1("John");
cout<<"Number of Student objects created: "<<Student::getObjectsCreated()<<endl;
//creating another Student, now the value must be 2
Student s2("James");
cout<<"Number of Student objects created: "<<Student::getObjectsCreated()<<endl;
//creating another Student, now the value must be 3
Student s3("Oliver");
cout<<"Number of Student objects created: "<<Student::getObjectsCreated()<<endl;
//note that static members can be called using class name (no need to create an object)
//you can also access objects field by Student::objects since objects is public
//also, there is no problem calling using an object. i.e s3.objects or s3.getObjectsCreated()
//are both valid statements
return 0;
}
/*OUTPUT*/
Number of Student objects created: 0
Number of Student objects created: 1
Number of Student objects created: 2
Number of Student objects created: 3