How to write a destructor for this class?

class foo{
public:
foo(int i); //creates a vector of size i
~foo);

private:
vector<int> vec;
}

foo::foo(int i){
vec.assign(i, 0);
}

foo::~foo(){
//what to write here???
//Do I need a destructor for this class, at all ?
}
There is no need to write your own destructor for this class, unless you want some sort of special behavior (e.g. a screen output)

Incidentally, your constructor first consructs an empty vector and then calls vector::assign(). You could just construct it directly with foo::foo(int i) : vec(i) {}
Cubbi,

Thanks for the reply! So, is it because vector is STL container and so, even though it does dynamic memory allocation, the compiler will take care of that?

Yeah you are right, I need to start using initializer lists more.
vector's destructor will take care of the cleanup.

You can assume that all properly encapsulated classes will do their own cleanup. You typically only need to worry about cleanup if:

1) You are doing your own memory allocation
2) You are using an API which does not have encapsulated objects (typically C APIs, like WinAPI, SDL, etc)

STL containers are all properly encapsulated and will clean up after themselves.

EDIT: also, you do not need to call vector's dtor explicitly (and you shouldn't!) This is done automatically by the compiler.
Last edited on
Thanks Disch. That makes it clearer.
Topic archived. No new replies allowed.