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

Question #252384

Write C++ program to count the number of objects created and destroyed for a class using 

static data members and static member functions.


1
Expert's answer
2021-10-16T13:52:55-0400
#include <iostream>

/**
Write C++ program to count the number of objects created and destroyed 
for a class using 
static data members and static member functions.
*/

class Base {
public:
    Base() {
        created++;
    }

    virtual ~Base() {
        destroyed++;
    }

    static int CtorCalls() {
        return created;
    }
    static int DtorCalls() {
        return destroyed;
    }

private:
    static int created;
    static int destroyed;
};

int Base::created = 0;
int Base::destroyed = 0;


int main() {
    {
        Base arr[10];
        Base another_one;
    }
    std::cout << "Ctors calls: " << Base::CtorCalls() << "\n";
    std::cout << "Dtors calls: " << Base::CtorCalls() << "\n";
    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