Answer to Question #185803 in C++ for ismail khan

Question #185803

Write a program that defines a class with a data member to 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 about its serial number. They should respond I am object number 2, and so on



1
Expert's answer
2021-04-26T10:32:26-0400
#include <iostream>

class Identifiable {
    private:
        int serialNumber;
    public:
        static int lastSerial;
    public:
        Identifiable();
        ~Identifiable();
        void reportSerial() const;
};

Identifiable::Identifiable() {
    lastSerial += 1;
    this->serialNumber = lastSerial;
}

Identifiable::~Identifiable() {}


void Identifiable::reportSerial() const {
    std::cout << "I am object number " << this->serialNumber << std::endl;
}

int Identifiable::lastSerial = 0;

int main() {
    Identifiable object1;
    Identifiable object2;
    Identifiable object3;

    object1.reportSerial();
    object2.reportSerial();
    object3.reportSerial();

    return 0;
}

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

ismail khan
26.04.21, 17:57

thank you very much sir

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS