What is the difference between declaring static variable inside a block and outside a block in a file? Eg, here, what is difference between static variables a,b,c,d? Can we
The following worked for me:
/*
* How to create an object on the stack.
* Also make sure that only 5 objects are created for the class
*/
#include
using namespace std;
class User {
private:
int id;
static int counter;
static bool isOk;
public:
User();
~User() {}
int getId() { return id; }
static int getCounter() { return counter; }
static bool getStatus() { return isOk; }
static void resetOk() { isOk = false; }
static void setOk() { isOk = true; }
};
User::User() {
if(counter == 5) {
cout << "Not allowed to create more than 5 objects" << endl;
resetOk();
return;
}
counter++;
id = counter;
setOk();
}
int User::counter = 0;
bool User::isOk = false;
int main()
{
// Create objects on stack
User user1;
(User::getStatus()) ? cout << "user1 id: " << user1.getId() << endl :
cout << "Object Construction Failed" << endl;
User user2;
(User::getStatus()) ? cout << "user2 id: " << user2.getId() << endl :
cout << "Object Construction Failed" << endl;
User user3;
(User::getStatus()) ? cout << "user3 id: " << user3.getId() << endl :
cout << "Object Construction Failed" << endl;
User user4;
(User::getStatus()) ? cout << "user4 id: " << user4.getId() << endl :
cout << "Object Construction Failed" << endl;
User user5;
(User::getStatus()) ? cout << "user5 id: " << user5.getId() << endl :
cout << "Object Construction Failed" << endl;
User user6;
(User::getStatus()) ? cout << "user6 id: " << user6.getId() << endl :
cout << "Object Construction Failed" << endl;
User user7;
(User::getStatus()) ? cout << "user7 id: " << user7.getId() << endl :
cout << "Object Construction Failed" << endl;
return 0;
}