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

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 0.85 KB  |  hits: 12  |  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. Are const class members useful when the assignment operator is overloaded?
  2. class A
  3. {
  4. public :
  5.    const int size;
  6.    A(const char* str) : size(strlen(str)) {}
  7.    A() : size(0) {}
  8. };
  9.  
  10.  
  11. A create(const char* param)
  12. {
  13.     return A(param);
  14. }
  15.  
  16.  
  17. void myMethod()
  18. {
  19.     A a;
  20.  
  21.     a = create("abcdef");
  22.     // do something
  23.  
  24.     a = create("xyz");
  25.     // do something
  26. }
  27.        
  28. class t_text {
  29. public:
  30. // ...
  31. public:
  32.     void setString(const std::string& p);
  33. private:
  34.     const t_text_attributes d_attributes;
  35.     std::string d_string;
  36. };
  37.        
  38. text.setString("TEXT"); // << Good: What you read is what happens.
  39. text = otherText; // << Bad: Surprise - attributes don't actually change!
  40.        
  41. class A
  42. {
  43. private:
  44.    const int a;
  45. public :
  46.    A() : a(0) {}
  47.    A& operator = (const A& other) {return *this;}
  48. };
  49.  
  50. int main()
  51. {
  52.    A a;
  53.    A b;
  54.    a = b; //this is legal if operator = is declared
  55. }