I have been researching, and nothing relevant has come up, so I came here.
I am trying to avoid memory leaks, so I am wondering:
Say I have class MyClass
with member int
s a
and b
, and an int array c
, which are filled in a member function:
class MyClass
{
public:
int a, b;
int c[2];
void setVariables()
{
a, b = 0;
for (int i = 0; i < 2; i++)
{
c[i] = 3;
}
}
};
int main(int argc, char* argv[])
{
MyClass* mc = new MyClass();
mc->setVariables();
delete mc;
}
Now, after I call delete mc
, will a
, b
, and all the contents of c
be deleted as well? Or will I have to do that explicitly in the destructor of MyClass
?
When
delete mc
is executed, the compiler calls the destructor of the object (MyClass::~MyClass()
) and then deallocates the memory associated with it.The default destructor (when you don't declare your own) calls the destructors of all member variables, in order from last to first by declaration (that is, in this case,
c
, thenb
, thena
). Since those members in this example are POD types (they do not have a destructor), no work is done.When you free an object, all of its member variables are automatically freed as well. So, in your case, yes,
a
,b
andc
are all freed.However, if one of your member variables is a pointer, only the pointer itself is automatically freed, not the object it points to - this is the most common case for having to write your own destructor.