Answer to Question #198861 in C++ for Ali raza

Question #198861

Write a program that counts the number of objects created and destroyed using constructer and destructor.



1
Expert's answer
2021-05-27T19:30:00-0400
#include <iostream>
using namespace std;

class MyClass
{
private:    
    static int count;
    
public:


    //default constructor
    MyClass()
    {
        ++count; //Increment count when object is created
    }
    
    MyClass(const MyClass&)
    {
        ++count;
    }
    
    //Destructor
    ~MyClass()
    {
        --count; //Decrement when object goes out of scope
    }
    //Static method to maintain number count number of objects
    static int counter()
    {
        return count;
    }
};


int MyClass::count = 0;


int main()
{
    cout<<"Starting"<<endl;
    cout << "1. Current object(s): " << MyClass::counter()<<endl;
    {
        MyClass mc1;
        cout<<"2. Current object(s): "<<MyClass::counter()<<endl;
    }
    
    cout <<"3. Current object(s): "<<MyClass::counter()<<endl;

    MyClass* ptr1 = new MyClass();
    cout <<"4. Current object(s): "<<MyClass::counter()<<endl;
   
    delete ptr1;


    cout <<"5. Current object(s): "<<MyClass::counter()<<endl;
    {
        MyClass mc1;
        MyClass mc2 = mc1;


        cout<<"6. Current object(s): "<< MyClass::counter()<<endl;
    }
    
    cout <<"7. Current object(s): "<<MyClass::counter()<<endl;
    cout<<"End";
    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

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog