Solutions

Print “I am object number –” | [Solved] | Classes | OOP | C++

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 about its serial number. They should respond I am object number 2, and so on.

Coding

#include<iostream>
using namespace std;
class counter
{
 private:
   static int count;
   int num;
 public:
   counter()
     {
         static int count;
         num=++count;
     }
   void show()
     {
         cout<<"I am Oject "<<num<<"\n";
     }
};
int counter :: count=0;
int main()
    { 
        counter x[3];
        for(int i=0;i<3;i++)
            {
               x[i].show();
            }
    }

Output

counter class oop

About the author

Syed Moin Ali

Hello My Name is Syed Moin Ali and I am the founder of PC Learnings Here on this blog I write about Blogging, SEO, Internet Tricks, Social Networking Site, and Make Money

Add Comment

Click here to post a comment