Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- using namespace std;
- class Ball
- {
- public:
- int a;
- Ball()
- {
- a = 0;
- }
- ~Ball()
- {
- cout << "destroyed Ball()" << endl;
- }
- };
- class Example
- {
- public:
- string name;
- Ball* b;
- Example()
- {
- name = "";
- b = NULL;
- }
- ~Example()
- {
- cout << "destroying Example()" << endl;
- delete b;
- }
- };
- void testfunction(vector<Example>& list)
- {
- cout << "entered testfunction1()" << endl;
- Example y;
- y.name = "myName";
- y.b = new Ball();
- y.b->a = 5;
- cout << "y.b->a = " << y.b->a << endl;
- list.push_back(y);
- cout << "exit testfunction1()" << endl;
- }
- void testfunction2()
- {
- cout << "entered testfunction2()" << endl;
- Example* y = new Example();
- cout << "exit testfunction2()" << endl;
- }
- int main() {
- vector<Example> list;
- testfunction(list);
- //testfunction2();
- if(list[0].b == NULL)
- cout << "b is null" << endl;
- else
- cout << "b is not null" << endl;
- cout << list[0].name << endl;
- cout << list[0].b << endl;
- cout << "list[0].b->a = " << list[0].b->a << endl;
- return 0;
- }
- Example(const Example& a)
- {
- name = a.name; // attention no dynamic allocation
- cout << "copy" <<endl;
- if (a.b) {
- b = new Ball(*a.b); // create a new duplicated Ball
- }
- else b = NULL;
- }
- void testfunction(vector<Example>& list)
- {
- // ...
- Example y;
- y.name = "myName";
- y.b = new Ball();
- y.b->a = 5;
- list.push_back(y);
- // ...
- } // <-- destructor for Example y is called and y.b is deleted
Add Comment
Please, Sign In to add comment