Suppose I have a C++ class with two private variables. A fixed size array, data, and a pointer to that array, pnt.
class MyClass
{
private:
double *pnt;
double data[2];
public:
myClass();
virtual ~MyClass();
double* getPnt() const;
void setPnt(double* input);
};
MyClass::MyClass()
{
double * input;
data[0] = 1;
data[1] = 2;
input= data;
setPnt(input);
}
MyClass::~MyClass()
{
delete this->pnt; // This throws a runtime error
}
void MyClass::setPnt(double * input)
{
pnt = input;
}
double * MyClass::getPnt() const;
{
return pnt;
}
int main()
{
MyClass spam; // Construct object
delete spam; // Error C2440: 'delete' cannot convert from 'MyClass' to 'void*'
}
There are two problems with this code. First if I try to call delete on the object, I get:
Error C2440: ‘delete’ cannot convert from ‘MyClass’ to ‘void*’
Secondly, if I comment out the delete statement, I get a realtime error stating a debug assertion failed! and this:
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
My question is then: For a class with a pointer to a private fixed size array, how do I properly free memory, write/call the destructor?
P.S I can’t use vector or nice containers like that (hence this question).
I see no static array. I see a fixed-size array. Also memory for
datais allocated as part of the object.You must not explicitely delete a member of the class: the delete operator will take care of that IFF the instance was dynamically allocated.
vs.