Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 28th, 2012  |  syntax: None  |  size: 1.70 KB  |  hits: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. C   Class isn't returning the correct value of my private variable
  2. #include <iostream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. class MyClass
  8. {
  9.  
  10.     private:
  11.         int privateVariable;
  12.  
  13.     public:
  14.         int userVariable;
  15.  
  16.     void setVariable(int userVariable)
  17.     {  
  18.         privateVariable = userVariable;            
  19.     }
  20.  
  21.     int getVariable()
  22.     {
  23.         return privateVariable;                    
  24.     }
  25.  
  26. };
  27.  
  28. int main()
  29. {
  30.     int userVariable;
  31.     cin >> userVariable;
  32.  
  33.     MyClass object1;
  34.     MyClass object2;
  35.  
  36.     object1.setVariable(userVariable);        
  37.     object2.getVariable();                  
  38.  
  39.     cout << object2.getVariable();            
  40.  
  41.     system("PAUSE");
  42.  
  43.     return 0;
  44. }
  45.        
  46. object1.setVariable(5); // object1.privateVariable = 5
  47.                         // object2.privateVariable -> still uninitialized
  48. object2.getVariable();  // returns uninitialized variable
  49.        
  50. class MyClass
  51. {
  52. private:
  53.    static int privateVariable;
  54. //......
  55. }
  56.        
  57. class MyClass
  58. {
  59. private:
  60.    static int privateVariable;
  61. public:
  62.    static void setVariable(int userVariable)
  63.    {  
  64.       privateVariable = userVariable;            
  65.    }
  66.  
  67.    static int getVariable()
  68.    {
  69.       return privateVariable;                    
  70.    }
  71. };
  72.        
  73. MyClass::setVariable(5); //MyClass.privateVariable = 5;
  74. MyClass::getVariable(); //returns 5
  75. object1.getVariable(); //returns also 5
  76.        
  77. object1.setVariable(5); // object1.privateVariable = 5
  78.                             // object2.privateVariable -> still uninitialized
  79. object2.setVariable(5); //object2.privateVariable = 5
  80. object2.getVariable();  // returns 5
  81.        
  82. class MyClass
  83. {
  84. private:
  85.    static int privateVariable;
  86. //......
  87. public:
  88.    MyClass()
  89.    {
  90.       privateVariable = 5;
  91.    }
  92. }