Your problems come from here:
4 5 6 7 8 9
|
Geometry::Geometry(){
name = new char[20];
name = "Geometry Default N";
type = new char[20];
type = "Geometry Default T";
}
|
What does the operator
new[] do?
In fact, what is a pointer?
A pointer is a variable that stores a memory address.
A pointer is a bit like an
unsigned long int, but the number it stores represents a memory address.
So what does
new[] do? As in:
name = new char[20];
It allocates a chunk of memory and returns its memory address.
More specifically, in your case, it allocates memory for an array of 20
char's then returns the memory address of the first element of that array.
So far so good. But the problem is that you do:
1 2
|
name = new char[20];
name = "Geometry Default N";
|
The trick to understand is that
"Geometry Default N"
is a string literal. You can think of it as a nameless variable, and it too has a memory address.
So what happens is that you replace the memory address given by
new[] with the memory address of the string literal, and the string literal cannot be
delete[]'d.
Long story short: you cannot copy
char arrays by simple assignment, which is why in good old C the
strcpy() function exists, and in C++ there exists
std::string as a replacement of
char arrays and pointers.
So do what the C++ programmer does, and use
std::string.
1 2 3 4 5 6 7 8 9 10 11
|
#include <string>
class Geometry
{
private:
std::string name;
std::string type;
// ...
};
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include "Geometry.h"
Geometry::Geometry(){
// now this simply works
name = "Geometry Default N";
type = "Geometry Default T";
}
// ...
Geometry::~Geometry(){
// nothing needs to be done with regards to
// cleaning up this->name and this->type
}
|