Answer to Question #168988 in Java | JSP | JSF for Sambuddha Chakraborty

Question #168988

Create a class that includes a data member that holds a “serial number” for each 

object created from the class. That is, the first object created will be numbered 1, the 

second 2, and so on. To do this, you’ll need another data member that records a count 

of how many objects have been created so far. (This member should apply to the class 

as a whole; not to individual objects. What keyword specifies this?) Then, as each 

object is created, its constructor can examine this count member variable to determine 

the appropriate serial number for the new object. Add a member function that permits 

an object to report its own serial number. Then write a main() program that creates 

three objects and queries each one.



1
Expert's answer
2021-03-04T15:51:42-0500
#include <iostream>
using namespace std;

class CounterClass {
private:
static int counter;
int number;

public:
CounterClass() {
number = ++counter;
};

void tell_number() {
cout << "I am object " << number << endl;
};
};


int CounterClass::counter = 0;

int main() {
CounterClass obj1;
CounterClass obj2;
CounterClass obj3;
obj1.tell_number();
obj2.tell_number();
obj3.tell_number();
cin.get();
}
</iostream>

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog