My variables aren’t producing data like they should be. For whatever reason, my string is empty, yet when I try to execute my function, my character clearly passes the argument “holland” to the name parameter upon construction. Despite this, when I make a call to get_name(), the string is returned as empty. Ontop of that, I have a static integer called “character_count”, which is supposed to initialize at 0 and then increment upon every character creation to pass values to the character’s unique id. Despite this, it’s still not working as it should.
Could someone tell me please what I’m doing wrong?
here’s my 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)
{
char_id = char_count;
char_count++;
name = char_name;
race = char_race;
gender = char_gender;
}
Character::~Character()
{
}
std::string Character::get_name()
{
return this->name;
}
int Character::get_id()
{
return this->char_id;
}
Race Character::get_race()
{
return this->race;
}
Gender Character::get_gender()
{
return this->gender;
}
Here’s my header file:
#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();
std::string get_name();
Race get_race();
Gender get_gender();
private:
int char_id;
static int char_count;
std::string name;
Race race;
Gender gender;
};
#endif // CHARACTER_H
Here’s my main:
#include <QtCore/QCoreApplication>
#include <tinyxml/tinyxml.h>
#include "classowner.h"
#include "character.h"
int main(int argc, char *argv[])
{
std::string holland_name = "holland";
Character * holland = new Character(holland_name, HUMAN, MALE);
delete holland;
std::cout << "testing, mic...1, 2, 3...testing, testing. Bow, chica wow wowww!!1" << std::endl;
std::cout << holland->get_id() << std::endl; //outputs as an 8 digit letter, when it should be either 0, or 1.
std::cout << holland->get_name() << std::endl; //does not output at all.
return 0;
}
That’s because you delete the memory before you’ve finished with it. Try this instead
Only delete after you’ve finished with the object concerned. This kind of mistake invokes Undefined Behaviour, which means all bets are off and anything may happen when you run your code. In some ways you are lucky that there was an obvious error. Your program could have appeared to run successfully, and you would never have known there was a problem.