I need to get a number of created and the number of active class instances.
#include <iostream>
#include <stdexcept>
class Set {
double value;
int created = 0;
int active = 0;
public:
Set();
Set(double num);
static int NumberOfCreated();
static int NumberOfActive();
};
Set::Set() : value(0) {}
Set::Set(double num) : value(num) {
created++;
active++;
}
int Set::NumberOfCreated() { return created; }
int Set::NumberOfActive() { return active; }
int main() {
Set s1, s2(100);
{ Set s3(50); } // After "}", "s3" doesn't exist anymore
std::cout << Set::NumberOfCreated(); // Should print 3
std::cout << Set::NumberOfActive(); // Should print 2
return 0;
}
I get two errors:
invalid use of member ‘Set::created’ in static member function
invalid use of member ‘Set::active’ in static member function
Also, this logic would always give the same output for active and created class instances. Could you give me a better approach to how to find number of active elements?
- Note:
mainfunction cannot be changed! Only class should be changed to enable this functionality.
>Solution :
you have multiple problems, here is how it can be done, check comments:
#include <iostream>
#include <stdexcept>
class Set {
double value;
static int created; // you need single variable for all instances, this is why static
static int active;
public:
Set();
Set(double num);
~Set() {
--active; // destructor is called when object is destroyed, so number of active instances is decreased
}
static int NumberOfCreated();
static int NumberOfActive();
};
int Set::created = 0;
int Set::active = 0;
Set::Set() : Set(0) {} // this constructor should increase created/active counters as well, this can be achieved via calling another ctor
Set::Set(double num) : value(num) {
created++;
active++;
}
int Set::NumberOfCreated() { return created; }
int Set::NumberOfActive() { return active; }
int main() {
Set s1, s2(100);
{ Set s3(50); }
std::cout << Set::NumberOfCreated() << std::endl;
std::cout << Set::NumberOfActive() << std::endl;
return 0;
}
and of course follow @user17732522 comments about copy/move and thread safety