I'm sorry if this is in the wrong forum but I have a problem with my program.
For some reason it crashes when I'm trying to assign a string in a constructor.
I'm pretty new to c++ so I'm not sure what I'm doing wrong.
Card.h
#ifndef CARD_H
#define CARD_H
#include "allegro.h"
#include <iostream>
#include <string>
using std::ostream;
using std::string;
class Card {
public:
Card();
Card(string cname,unsigned short lvl, unsigned short atr,unsigned short atk,unsigned short def,char *f);
~Card ();
unsigned short level;
unsigned short attribute;
unsigned short attack;
unsigned short defense;
BITMAP *picture;
string card_name;
};
#endif
One possibility is that you messed up elsewhere, but the effects of a mistake that say, writes into memory that should not be written to at that point, surfaces when you try to assign a non-empty string to the card_name member variable.
By the way, passing std::string objects by (const) reference unless you really want to make a copy. The filename parameter probably should be a const char*. Oh, and use the constructor initialisation list instead of assigning in the constructor body.
You should not use using declarations (e.g., using std::string) and using directives (e.g., using namespace std) in a header file except within some restricted scope.
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
I'm sorry if this is in the wrong forum but I have a problem with my program.
For some reason it crashes when I'm trying to assign a string in a constructor.
And at the same time, you're including <vector>? Why not just use vector instead of all that code above? You are doing exactly what vector is supposed to do. You repeat the same kind of coding in other places. Replace any code that looks like this and just use vector. It makes no sense to be coding your own dynamic arrays, and at the same time, your code is using a class that does dynamic arrays, i.e. vector.
Regards,
Paul McKenzie
Last edited by Paul McKenzie; May 31st, 2009 at 08:11 AM.
Good catch, especially since Card is not a POD type so the memcpy() is suspect.
Right. The memcpy() invokes undefined behaviour, since Card is non-POD.
Ishida, you cannot use memcpy() on an array of Card objects. The Card object contains a std::string, therefore the only way to copy is to use the proper copy construction and assignment.
That's why "pakk" should either be a vector<Card> or vector<Card*>, more than likely a vector<Card*> due to the BITMAP* member in the Card class.
The only subtlety to be aware of is that if you don't define your open copy constructor and operator=, it will be possible for multiple Cards to share a pointer to the same BITMAP.
If that's not a problem, then don't worry about it.
Bookmarks