Bloomberg LP Interview Question
Software Engineer / DevelopersAn approach that's both easy to implement and that gives the right answer is to create a static counter in Widget, increment the counter each time a Widget constructor is called, and decrement it whenever the Widget destructor is called. You also need a static member function how many to report how many Widgets currently exist. If Widget did nothing but track how many of its type exist, it would look more or less like this:
class Widget {
public:
Widget() { ++count; }
Widget(const Widget&) { ++count; }
~Widget() { --count; }
static size_t howMany()
{ return count; }
private:
static size_t count;
};
// obligatory definition of count. This
// goes in an implementation file
size_t Widget::count = 0;
Apart from that ,
- technicolor January 28, 2009it even has to incremented in the copy constructor.