Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. class MyThing
  7. {
  8. public:
  9. /*
  10. * Have to override default constructor to initialize const and reference members.
  11. * Note mVarValue doesn't have to be explicitly initialized. Args almost
  12. * always have to be passed to initialize these members.
  13. */
  14. explicit
  15. MyThing(const string& refValue) : mConstValue(0), mRefValue(refValue) {}
  16.  
  17. /* Default copy constructor is usually OK.
  18. MyThing(const MyThing& other) :
  19. mConstValue(other.mConstValue),
  20. mRefValue(other.mRefValue),
  21. mVarValue(other.mVarValue) {}
  22. // */
  23.  
  24. /*
  25. * Have to override default assignment operator and ignore these members.
  26. */
  27. //*
  28. MyThing& operator=(const MyThing& other)
  29. {
  30. mVarValue = other.mVarValue;
  31. // can't assign const/ref once initialized
  32. return *this;
  33. }
  34. // */
  35.  
  36. private:
  37. const int mConstValue;
  38. const string& mRefValue;
  39. string mVarValue;
  40. };
  41.  
  42. int
  43. main(int arc, char** argv)
  44. {
  45. // If anything ever actually uses mRefValue, this memory has to still
  46. // be around (up to the caller).
  47. string name("thing");
  48.  
  49. // constructor
  50. MyThing thing(name);
  51.  
  52. // copy constructor
  53. MyThing otherThing(thing);
  54.  
  55. // assignment operator
  56. otherThing = thing;
  57.  
  58. return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement