Destructor in derived class / freeing memory

Hello, i have a short question on the way the destructor is called and used in a derived class ...
Say i have a class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class clMem{
public:
// ctor
int len;
int* vec;
    clMem(int len){

        this-> vec = (int*)malloc(sizeof(int)*len);

    }
    ~clMem(){
        free(vec);
    }

};

Oldfashioned ... OK ...

Now, i want a derived class with an additional vector and i adjust the constructor
1
2
3
clMem2(int len) : clMem(len){
    vec2 = (int*malloc(sizeof(int)*len);
}



Well first question: is the dynamic allocation of the constructor of "clMem" done here as well ? I think so, and i will find out easily.

But, more important:
What will the destructor of the derived class look like: Do i have to free both pointers, or only the additional, as there is already a destructor for the "parent" class ??

... Well thanks in advance ... and
Last edited on
Well first question: is the dynamic allocation of the constructor of "clMem" done here as well ?


Yes. That is what you're doing here:

1
2
3
clMem2(int len)
  : clMem(len)  // <-  this calls the parent class ctor
{


What will the destructor of the derived class look like: Do i have to free both pointers, or only the additional


clMem2 only needs to clean up with clMem2 allocated. It does not have to worry about the parent class -- the parent class will clean up its own allocations:

1
2
3
4
/*virtual*/ ~clMem2()
{
    free(vec2);
}


The 'virtual' keyword here is optional. Use it if you want the class to be polymorphic.
Thanks for the answer. That solves my issue.
I don't know much about polymorphism and such stuff.
Well, i'll come to that chapter, but for now i'm done with my destructor.

thanks a lot and have a nice day,

....
Topic archived. No new replies allowed.