fork download
  1. #include <iostream>
  2.  
  3. class NonStaticVariable
  4. {
  5. public:
  6. NonStaticVariable();
  7. unsigned int get_count();
  8. void decrement_count();
  9. private:
  10. unsigned int count;
  11. };
  12.  
  13. class StaticVariable
  14. {
  15. public:
  16. StaticVariable();
  17. unsigned int get_count();
  18. void decrement_count();
  19. private:
  20. static unsigned int count;
  21. };
  22.  
  23. unsigned int StaticVariable::count = 0;
  24.  
  25. NonStaticVariable::NonStaticVariable()
  26. {
  27. this->NonStaticVariable::count = 0;
  28. ++this->NonStaticVariable::count;
  29. }
  30.  
  31. unsigned int NonStaticVariable::get_count()
  32. {
  33. return this->NonStaticVariable::count;
  34. }
  35.  
  36. void NonStaticVariable::decrement_count()
  37. {
  38. --this->NonStaticVariable::count;
  39. }
  40.  
  41. StaticVariable::StaticVariable()
  42. {
  43. ++this->StaticVariable::count;
  44. }
  45.  
  46. unsigned int StaticVariable::get_count()
  47. {
  48. return this->StaticVariable::count;
  49. }
  50.  
  51. void StaticVariable::decrement_count()
  52. {
  53. --this->StaticVariable::count;
  54. }
  55.  
  56. int main(int argc, char *argv[])
  57. {
  58. // I will create two `NonStaticVariable` objects, but the count of each one will be just 1, and if I decrement the count of one of them, then one will have a count of 0 and the other will have a count of 1.
  59. NonStaticVariable Var1, Var2;
  60. std::cout << Var1.get_count() << " " << Var2.get_count() << std::endl;
  61. Var1.decrement_count();
  62. std::cout << Var1.get_count() << " " << Var2.get_count() << std::endl;
  63.  
  64. // I will create two `StaticVariable` objects, and since their `count` member variable is shared, the count of both will be equal to two, and if I decrement the count of one of them, then both will be equal to one.
  65. StaticVariable Var3, Var4;
  66. std::cout << Var3.get_count() << " " << Var4.get_count() << std::endl;
  67. Var3.decrement_count();
  68. std::cout << Var3.get_count() << " " << Var4.get_count() << std::endl;
  69. return 0;
  70. }
  71.  
Success #stdin #stdout 0.02s 2724KB
stdin
Standard input is empty
stdout
1 1
0 1
2 2
1 1