Help Out A Noob-Con/Destructers(C++)

Started by
13 comments, last by CarlosNYM 16 years, 9 months ago
Hello everyone! In my quest for infinte C++ knowledge I have run into one tricky little piece of code. The example that the online book gives is really confusing and makes no sense. I have a piece of code that has a working class in it, and I was wondering if someone could put a constructer and destructer in it, it could help me learn it better. Also, what exactly do they do? Will all classes I use in games I have constructer and destructer? #include<iostream> using namespace std; class character { public: void askName(); int getHp(); int getMp(); int getatk(); int getdef(); private: string name; int level; int hp; int mp; int atk; int def; }; void character::askName() { cout<<"What is your name "; getline(cin,name); cout << "\n\n You choose " << name; } int main() { character dude; cout<<"Welcome to my RPG! \n\n"; dude.askName(); system("pause"); }
Advertisement
A constructor and destructor are called whenever the an instance of the class is made/destroyed respectively.

For example:

//in foo.hclass foo{public:    foo();    //constructor    ~foo();   //destructor     int bar;};//and in foo.cppfoo::foo(){    bar = 0;}foo::~foo(){}//in main.cpp or somewhere elsefoo *myFoo = new foo();myFoo->bar += 5;std::cout << myFoo->bar << std::endl;


The output would be 5 since bar was initialized to 0 in the constructor and increased by 5.
That was a very simple example. Constructors/destructors can be pretty useful if you implement them correctly. I like to put my initialization stuff in constructors and delete stuff, etc in the destructor.

Like in your code you could init the character attributes (level, etc) to make sure they are initialized properly before using them.
class MyClass{public:MyClass() { std::cout << "This is the constructor \n It is named after the class and does not return a value, nor is declared void. \n I am run whenever a variable of my class type is created. \n I can be called to declare variables and run little bits of code important to initializing my class. " << std::endl; }~MyClass() { std::cout << "This is the destructor \n I am named after the class name and am recognized by the tilde symbol in front of my name \n I am called whenever a variable of my class type is destroyed. \n I can be used to cleanup anything that needs to be manually deleted." << std::endl; }};


Generally in the examples from books I've seen, classes are just declared with default constructors and destructors ( MyClass(); ~MyClass(); ) for use to reference to, and/or so you don't forget that they exist.
That's my opinion.
(Disclaimer: I'm sure this will be corrected/added to)

Constructors are used for initialising your classes - if an instance of this class is created, the constructor _will_ be called, so you can use it to make sure the class variables have sensible values in them, or to allocate memory your class might need.

A destructor is a bit of code that _will_ be called when an instance of your class is destroyed- so a good place to clean up any memory you might have, and to ensure things are shut down correctly.

In your case, a destructor isn't really needed, but for the constructor you could have something like this:
class character{private:    string name;    int level;    int hp;    int mp;    int atk;    int def;public:    void askName();    int getHp();    int getMp();    int getatk();    int getdef();    character(){        level = 0;        hp = 0;        mp = 0;        atk = 0;        def = 0;    }};

So, when it comes to game design, what exactly would I be deleting? Variables that are not being used anymore at a certain point in a game?
I'm not too experienced with classes, but I would say: You would delete any variables that you have allocated on the heap using the new keyword.

class::class(){int *number = new int(5);}class::~class(){delete number;}


Correct me if that's wrong.

BTW: The 5 in parenthesis is the value that will be put into memory initially.

How do I put code into the code boxes like above?
"If I were a philosopher, I might argue that an array name's type is not equivalent to its equivalent. But I'm not a philosopher, so when I suggest something like that, I'm not a philosopher; I'm only being equivalent to a philosopher.""Saturn ascends, choose one or ten. hang on or be humbled again." - Tool
Quote:Original post by cemedias
I'm not too experienced with classes, but I would say: You would delete any variables that you have allocated on the heap using the new keyword.

class::class(){int *number = new int(5);}class::~class(){delete number;}


Correct me if that's wrong.


Yeah, that's wrong. You've created a new pointer on the stack and allocated memory to it -- what you have there is a memory leak. You need to delete any allocated memory before all pointers to it have gone out of scope. Also, your destructor either deletes memory that has not been allocated (since the pointer to allocated memory was created on the stack of the constructor) or you're going to get a nasty compiler error because "number" is not defined in your class. This would be correct:

class myclass{  int *intpointer;  class(){    intpointer = new int(5);  }  ~class(){    delete intpointer;  }};
Quote:Original post by cemedias
How do I put code into the code boxes like above?


[ source ] and [ /source ] tags without the spaces.

I wrote this code,and it's not working. When I wrote the constructer and destructer within the class and it worked but when I wrote those functions outside of the class it didn't work. I don't really get how those work. Also where are you supposed call the destructer function? In main right before a return 0; statement?
#include&lt;iostream&gt;using namespace std;class character{private: string name; int level; int hp; int mp; int atk; int def;public: void askName(); int getHp(); int getMp(); int getatk(); int getdef();  character() {          }  ~character() { } };character::character(){ int level=1; int hp=0; int mp=0; int atk=0; int def=0;  }character::~character(){}void character::askName(){cout<<"What is your name ";getline(cin,name);cout << "\n\n You choose " << name;     }int main(){ character dude; cout<<"Welcome to my RPG! \n\n"; dude.askName(); system("pause");}
Quote:Original post by CrimsonSun
Quote:Original post by cemedias
I'm not too experienced with classes, but I would say: You would delete any variables that you have allocated on the heap using the new keyword.

class::class(){int *number = new int(5);}class::~class(){delete number;}


Correct me if that's wrong.


Yeah, that's wrong. You've created a new pointer on the stack and allocated memory to it -- what you have there is a memory leak. You need to delete any allocated memory before all pointers to it have gone out of scope. Also, your destructor either deletes memory that has not been allocated (since the pointer to allocated memory was created on the stack of the constructor) or you're going to get a nasty compiler error because "number" is not defined in your class. This would be correct:

class myclass{  int *intpointer;  class(){    intpointer = new int(5);  }  ~class(){    delete intpointer;  }};


Thanks, I understand now.

@ blakedev: Oh I see. I was putting instead of [ source ]
"If I were a philosopher, I might argue that an array name's type is not equivalent to its equivalent. But I'm not a philosopher, so when I suggest something like that, I'm not a philosopher; I'm only being equivalent to a philosopher.""Saturn ascends, choose one or ten. hang on or be humbled again." - Tool

This topic is closed to new replies.

Advertisement