Answer to Question #247519 in C++ for Elena

Question #247519
Write a program to create a class for counting the number of objects created
and destroyed within various block using static data member, constructor
and destructors.
1
Expert's answer
2021-10-06T06:17:09-0400
#include <iostream>
using namespace std;
class Counter{


    public:
    static int created;
    static int destroyed;
    Counter(){
        created++;
    }
    ~Counter(){
        destroyed++;
        cout<<"Destroyed so far: "<<Counter::destroyed<<endl;
    }
};
int Counter::created = 0;
int Counter::destroyed = 0;


int main(){
    cout<<"Created so far: "<<Counter::created<<endl;
    Counter c1, c2;
    
    cout<<"Created so far: "<<Counter::created<<endl;
    Counter c3;



    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
APPROVED BY CLIENTS