Reputation: 1738
I'm trying to create deep copy of instance of my class via copy constructor, but I can't figure out, how to write it.. In this moment, When I call copy constructor, the programm doesn't crash, nevertheless when I want to do anything with the instances (ie print the array, add some item to it, etc.) then the programme crashes...
Could anybody please show me, how to write it properly? It's driving me crazy yet O_o
struct DbChange {
const char* date;
const char* street;
const char* city;
};
class DbPerson {
public:
DbPerson(void);
const char* id;
const char* name;
const char* surname;
DbChange * change;
int position;
int size;
};
DbPerson::DbPerson() {
position = 0;
size = 1000;
change = new DbChange[1000];
}
class Register {
public:
// default constructor
Register(void);
int size;
int position;
DbPerson** db;
//copy constructor
Register(const Register& other) : db() {
db= new DbPerson*[1000];
std::copy(other.db, other.db + (1000), db);
}
};
int main(int argc, char** argv) {
Register a;
/*
* put some items to a
*/
Register b ( a );
a . Print (); // now crashes
b . Print (); // when previous line is commented, then it crashes on this line...
return 0;
}
Upvotes: 1
Views: 143
Reputation: 393799
Since the code shown in no way allows us to guess what Print does, and why it chashes, I'll just show you how I'd expect things to be in C++ (instead of an awkward mix between C and Java):
http://liveworkspace.org/code/4ti5TS$0
#include <vector>
#include <string>
struct DbChange {
std::string date;
std::string street;
std::string city;
};
class DbPerson {
public:
DbPerson(void);
std::string id, name, surname;
int position;
std::vector<DbChange> changes;
size_t size() const { return changes.size(); }
};
DbPerson::DbPerson() : position(), changes() { }
class Register {
public:
size_t size() const { return db.size(); }
int position; // unused?
std::vector<DbPerson> db;
Register() = default;
//copy constructor
Register(const Register& other) : db(other.db)
{
// did you forget to copy position? If so, this would have been the
// default generated copy constructor
}
void Print() const
{
// TODO
}
};
int main() {
Register a;
/*
* put some items to a
*/
Register b(a);
a.Print(); // now crashes
b.Print(); // when previous line is commented, then it crashes on this line...
return 0;
}
Upvotes: 4