I've got a simple class called object
that I'm having a problem with. Theres one method which causes a segfault if I call it. I don't understand why.
typedef class object
{
private:
short id;
std::string name;
SDL_Rect offset;
public:
object();
object(short i, std::string n);
~object();
object(const object &o);
object& operator = (const object &o);
std::string get_name();
void set_name(std::string n);
} object;
object::object()
{
id = 0;
name = "";
offset.x = 0;
offset.y = 0;
offset.w = 0;
offset.h = 0;
}
object::object(short i, std::string n)
{
id = i;
name = n;
offset.x = 0;
offset.y = 0;
offset.w = 0;
offset.h = 0;
}
object::~object()
{
delete &offset;
delete &id;
delete &name;
}
object& object::operator=(const object &o)
{
if(this != &o)
{
delete &name;
name.assign(o.name);
delete &id;
id = o.id;
delete &offset;
offset = o.offset;
}
return *this;
}
object::object(const object &o)
{
id = o.id;
name = o.name;
offset = o.offset;
}
// Functions
std::string object::get_name()
{
return name;
}
void object::set_name(std::string n)
{
name = n;
}
And my main.cpp
int main( int argc, char** argv )
{
struct object *a = new object(0, "test");
struct object *b = new object(1, "another test");
printf(a->get_name().c_str());
printf("\n");
printf(b->get_name().c_str());
b = a;
printf("\n");
printf(b->get_name().c_str());
a->set_name("Another test");
printf("\n");
printf(a->get_name().c_str());
delete a;
printf("\nDeleted a");
delete b;
printf("\nDeleted b");
return 0;
}
If I call a->set_name("Another test");
, I get a segfault. If I leave out the call, no problems, everything works. I'm probably missing something simple, but I can't find it. It doesn't segfault on the assignment, but if that line is there it crashes when deleting the pointer.