what is the logic to count number of objects created implicitly and explicitly inside the same program..Please help.

Recommended Answers

All 6 Replies

Start with the number zero, and each time an object is created, add one.

That's the logic.

If you mean something like creating a class, and counting how many times an object of that class is created, put the functionality to do the counting inside the constructor and make the counter shared across all instances (for example, by making it static).

As far as I know, these is no "standard" way to do that. What precisely are you trying to do, other than count the number of object that have been instantiated?

Surely something like this..?

If you have a static variable called "counter" and then increment it by 1 each time the constructor is called then this should work.

#include <iostream>

using namespace std;

class Foo {

    public:

    Foo()
    {
        counter++;
    }

    int getCount()
    {
        return this->counter;

    }
    protected:
    static int counter;
};

int Foo::counter = 0;
int main(int argc, char *argv[]) {

    Foo f;
    Foo b;
    cout << Foo::getCount() << endl;
}

The above is just an example to demonstrate. :)

Don't forget that you will need to add the counter increment to the copy constructor and the assignment operator. You probobly want to have that as a seperate counter since those objects will be implicitly created.

Just realised the above code wouldn't work. This will:

#include <iostream>

using namespace std;

class Foo {

    public:

    Foo()
    {
        counter++;
    }

    static int getCount()
    {
        return counter;

    }
    protected:
    static int counter;
};

int Foo::counter = 0;
int main(int argc, char *argv[]) {

    Foo f;
    Foo b;
    cout << Foo::getCount() << endl;
}

My bad :) http://ideone.com/X5GPKA e.g.

Thanks a lot for solving the problem.:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.