0

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

Edited by laavanya: wrong sentence

5
Contributors
6
Replies
34
Views
3 Years
Discussion Span
Last Post by laavanya
0

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).

0

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?

0

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. :)

Edited by phorce

0

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.

0

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.

0

Thanks a lot for solving the problem.:)

Edited by laavanya: spelling mistake

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.