My execution program won’t work properly, for whatever reason.
#include <QtCore/QCoreApplication>
#include <tinyxml/tinyxml.h>
#include "classowner.h"
#include "character.h"
int main(int argc, char *argv[])
{
Character * holland = new Character("Holland", HUMAN, MALE);
delete &holland;
std::cout << "Hello, World!" << std::endl;
return 0;
}
All my output states is that the program won’t execute properly. The output doesn’t display, however when I don’t allocate the object, it will. Obviously, it’s the object. What am I doing wrong?
Update
It appears the problem may be something more than deleting and allocating memory. Thus, I’m going to post the implementation behind the Character class.
Header:
#include <iostream>
#ifndef CHARACTER_H
#define CHARACTER_H
enum Race {HUMAN, DARK_ELF};
enum Gender {MALE, FEMALE};
class Character
{
public:
Character();
Character(std::string char_name, Race char_race, Gender char_gender);
~Character();
int get_id() { return this->char_id; }
std::string get_name() { return this->name; }
Race get_race() { return this->race; }
Gender get_gender() { return this->gender; }
private:
int char_id;
static int * char_count;
std::string name;
Race race;
Gender gender;
};
#endif // CHARACTER_H
//Source:
#include "character.h"
#include <iostream>
int * Character::char_count = 0;
Character::Character()
{
this->char_id = *char_count;
char_count++;
}
Character::Character(std::string char_name, Race char_race, Gender char_gender)
{
this->char_id = *char_count;
char_count++;
this->name = char_name;
this->race = char_race;
this->gender = char_gender;
}
Character::~Character()
{
}
First of all, you try to dereference a null pointer:
Both constructors of
class Characterdo thisand that’s an attempt to dereference a null pointer. That code makes no sense to me, I guess you could just use
intinstead of pointer:Also here:
you create an object of type
class Character. You have to delete that object through a pointer toclass Character– the pointer should have typeCharacter*. Instead you try to usedeleteon a pointer of typeCharacter**and that leads to undefined behavior.So instead of
you have to use