virtual copy constructor

closed account (j8Mo2yTq)
I know there is no such thing as a virtual copy constructor but the text im reading simulates that using a clone function. I just have a question regarding the last part of the code during its cleanup of the memory. I will list the working code below. what im asking about is in main function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
using namespace std;

class Fish {
public:
    virtual Fish* Clone() = 0;
    virtual void Swim() = 0;
    virtual ~Fish() {};
};

class Tuna: public Fish {
public :
    Fish* Clone() override {
        return new Tuna (*this);
    }

    void Swim() override final {
        cout << "Tuna swims fast in the sea" << endl;
    }
};

class BluefinTuna final:public Tuna {
public:
    Fish* Clone() override {
        return new Tuna (*this);
    }
};

class Carp final: public Fish {
public:
    Fish* Clone() override {
        return new Carp(*this);
    }
    void Swim() override final {
        cout << "Carp swims slow in the lake" << endl;
    }
};
int main(){
    const int ARRAY_SIZE = 4;
    Fish* myFishes[ARRAY_SIZE] = {NULL};
    myFishes[0] = new Tuna();
    myFishes[1] = new Carp();
    myFishes[2] = new BluefinTuna();
    myFishes[3] = new Carp();

    Fish* myNewFishes[ARRAY_SIZE];
    for (int index = 0; index < ARRAY_SIZE; ++index)
        myNewFishes[index] = myFishes[index]->Clone();

    // invoke a virtual method to check
    for (int index = 0; index < ARRAY_SIZE; ++index)
        myNewFishes[index]->Swim();

    // memory cleanup
    for (int index = 0; index < ARRAY_SIZE; ++index) {
        delete myFishes[index];
        delete myNewFishes[index];
        }
    return 0;
}


instead of writing

1
2
3
4
5
for (int index = 0; index < ARRAY_SIZE; ++index) {
     delete myFishes[index];
     delete myNewFishes[index];
     }


couldn't I just write

1
2
     delete[] myFishes;
     delete[] myNewFishes;
Lines 40 and 46:
 
Fish* myFishes[ARRAY_SIZE] = {NULL};

 
Fish* myNewFishes[ARRAY_SIZE];

Both of these arrays have automatic storage duration (i.e. you are not using 'new' to create these arrays). You should not call delete on the arrays themselves.

In each element of the array, you are assigning it a pointer to dynamic memory,
e.g. myFishes[0] = new Tuna();
These individual elements need to be cleaned up with delete, so you need to do delete myFishes[index];
Last edited on
closed account (j8Mo2yTq)
"you are not using 'new' to create these arrays" ahh I overlooked that thank you.
couldn't I just write
No. Even if the array where dynamically created using new all elements of that array are not destroyed when the array is destroyed. You need to delete the elements of the array with that for loop none the less.
Topic archived. No new replies allowed.