Re: Where to free memory ?
On Nov 9, 12:26 pm, Phil <pbruy...@yahoo.com> wrote:
Hello all,
I kindly request your help for the following problem.
Let's say I have two classes A and B defined as follows:
// ClassA.h //////////////////////////
class ClassA
{
public:
void ClassA(int nItems); // constructor
virtual ~ClassA();
protected:
double *myTable; // My table of nItems double values
}
Even with VC6, I would use std::vector<double> myTable
and get rid of the dynamic memory issues. But if you don't...
/////////////////////////////////////
// ClassA.cpp ///////////////////////
void ClassA(int nItems)
{
// Allocate memory for the table of double values
myTable=(double*)calloc(nItems, sizeof(double));
}
Assume this is:
void ClassA::ClassA(int nItems)
: myTable( (double *)calloc(..) )
{
if( myTable == NULL )
throw std::bad_alloc();
}
if you were using std::vector
void ClassA::ClassA(int nItems)
: myTable(nItems,0.0)
{}
~ClassA()
{
// Should I free the memory allocated for myTable here?
// free(myTable);
// myTable=NULL;
}
Yes you should free memory here. The myTable=NULL can
be omitted.
If you are using std::vector, you don't even need the dtor.
/////////////////////////////////////
// ClassB.h //////////////////////////
#include "ClassA.h"
class ClassB
{
public:
void ClassB();
protected:
ClassA classA(int nItems);
This is invalid. Should just be ClassA classA;
Or given the code below
ClassA *classA;
/////////////////////////////////////
// ClassB.cpp ///////////////////////
void ClassB()
{
classA=new ClassA(10);
// Do some processing here with classA
delete classA;
}
classA is not declared as a pointer in your example.
This should refuse to compile.