fork download
  1. namespace bad
  2. {
  3. class Data // always initializes its members, leaves no choice to the client code :(
  4. {
  5. private:
  6. int _i;
  7. float _f;
  8. void* _p;
  9.  
  10. public:
  11. Data() : _i(0), _f(0.f), _p(nullptr) { }
  12.  
  13. void SetI(int value) { _i = value; }
  14. void SetF(float value) { _f = value; }
  15. void SetP(void* value) { _p = value; }
  16.  
  17. double GetSomethingMeaningful() const { return !_p ? (_f * _i) : *(double*)_p; }
  18. };
  19. }
  20.  
  21. namespace good
  22. {
  23. class BasicData // base class for DataSafe and DataFast
  24. {
  25. protected:
  26. int _i;
  27. float _f;
  28. void* _p;
  29.  
  30. protected:
  31. BasicData() = default; // no initialization, leaves moosor!
  32. BasicData(int i, float f, void* p) : _i(i), _f(f), _p(p) { }
  33.  
  34. public:
  35. void SetI(int value) { _i = value; }
  36. void SetF(float value) { _f = value; }
  37. void SetP(void* value) { _p = value; }
  38.  
  39. double GetSomethingMeaningful() const { return !_p ? (_f * _i) : *(double*)_p; }
  40. };
  41.  
  42. class DataSafe : public BasicData // always initializes its members
  43. {
  44. public:
  45. DataSafe() : BasicData(0, 0.f, nullptr) { }
  46. };
  47.  
  48. class DataFast : public BasicData // no implicit members' initialization
  49. {
  50. };
  51. }
  52.  
  53. #include <iostream>
  54. using std::cout;
  55.  
  56. int main()
  57. {
  58. double d = 42.0;
  59. void* pd = (void*)&d;
  60.  
  61. {
  62. bad::Data obj;
  63. obj.SetI(2);
  64. obj.SetF(3.14);
  65. cout << obj.GetSomethingMeaningful() << '\n';
  66. }
  67.  
  68. {
  69. good::DataSafe obj;
  70. obj.SetF(3.14);
  71. cout << obj.GetSomethingMeaningful() << '\n';
  72. }
  73.  
  74. {
  75. good::DataFast obj;
  76. obj.SetP(pd);
  77. cout << obj.GetSomethingMeaningful() << '\n';
  78. }
  79. }
  80.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
6.28
0
42