Guest User

Untitled

a guest
Dec 13th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. class Ball
  7. {
  8. public:
  9. int a;
  10.  
  11. Ball()
  12. {
  13. a = 0;
  14. }
  15.  
  16. ~Ball()
  17. {
  18. cout << "destroyed Ball()" << endl;
  19. }
  20. };
  21.  
  22. class Example
  23. {
  24. public:
  25. string name;
  26. Ball* b;
  27.  
  28. Example()
  29. {
  30. name = "";
  31. b = NULL;
  32. }
  33.  
  34. ~Example()
  35. {
  36. cout << "destroying Example()" << endl;
  37. delete b;
  38. }
  39. };
  40.  
  41. void testfunction(vector<Example>& list)
  42. {
  43. cout << "entered testfunction1()" << endl;
  44.  
  45. Example y;
  46. y.name = "myName";
  47. y.b = new Ball();
  48. y.b->a = 5;
  49.  
  50. cout << "y.b->a = " << y.b->a << endl;
  51. list.push_back(y);
  52.  
  53. cout << "exit testfunction1()" << endl;
  54. }
  55.  
  56. void testfunction2()
  57. {
  58. cout << "entered testfunction2()" << endl;
  59. Example* y = new Example();
  60. cout << "exit testfunction2()" << endl;
  61. }
  62.  
  63. int main() {
  64. vector<Example> list;
  65. testfunction(list);
  66. //testfunction2();
  67.  
  68. if(list[0].b == NULL)
  69. cout << "b is null" << endl;
  70. else
  71. cout << "b is not null" << endl;
  72.  
  73. cout << list[0].name << endl;
  74. cout << list[0].b << endl;
  75. cout << "list[0].b->a = " << list[0].b->a << endl;
  76. return 0;
  77. }
  78.  
  79. Example(const Example& a)
  80. {
  81. name = a.name; // attention no dynamic allocation
  82. cout << "copy" <<endl;
  83. if (a.b) {
  84. b = new Ball(*a.b); // create a new duplicated Ball
  85. }
  86. else b = NULL;
  87. }
  88.  
  89. void testfunction(vector<Example>& list)
  90. {
  91. // ...
  92.  
  93. Example y;
  94. y.name = "myName";
  95. y.b = new Ball();
  96. y.b->a = 5;
  97.  
  98. list.push_back(y);
  99.  
  100. // ...
  101. } // <-- destructor for Example y is called and y.b is deleted
Add Comment
Please, Sign In to add comment