'terminate called after throwing an instance of 'std::bad_alloc' during initialization
header
struct Date
{
int year;
int month;
int day;
};
enum Department
{
Game,
FrontEnd,
Backend,
Operation,
HumanResource
};
class Employee
{
protected:
int id;
string name;
char gender;
Date entry_date;
string post;
Department dept;
int salary;
public:
Employee();
Employee(int id, const string& name, char gender, const Date& entry_date, string post, Department dept);
virtual ~Employee();
};
class Manager : public Employee
{
private:
int num_staff;
Employee** staffs;
public:
Manager();
Manager(int id, const string& name, char gender, const Date& entry_date, Department dept);
~Manager();
};
cpp
Manager::Manager(int id, const string &name, char gender, const Date &entry_date, Department dept) : Employee(id, name, gender, entry_date, post, dept), num_staff(0), staffs(NULL) {}
The program crashes here with complaint terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
Manager *pm1 = new Manager(101, "Bruce Wayne", 'M', Date{2016, 05, 10}, HumanResource);
I've spent tons of time solving it but failed. Anyone can help? thx in advance.
Update:
Employee::Employee(int id, const string& name, char gender, const Date& entry_date, string post, Department dept)
: id(id), name(name), gender(gender), entry_date(entry_date), post(post), dept(dept){};
Solution 1:[1]
The problem is likely because you have undefined behavior.
With your Manager constructor definition:
Manager::Manager(int id, const string &name, char gender, const Date &entry_date, Department dept)
: Employee(id, name, gender, entry_date, post, dept), num_staff(0), staffs(NULL) {}
you are first initializing the parent Employee class part, which is good. But when you do that, you pass the uninitilized post member variable as an argument to the Employee constructor.
Because post is uninitialized that will lead to the above mentioned undefined behavior.
This is exactly like initializing any variable with itself:
std::string post = post; // Makes no sense, and leads to UB
As for how to solve this, that really depends on your requirements. A simple solution would be to pass an empty string instead:
Manager::Manager(int id, const string &name, char gender, const Date &entry_date, Department dept)
: Employee(id, name, gender, entry_date, "", dept), num_staff(0), staffs(NULL) {}
If you enable more and extra warnings (for GCC and Clang I always recommend at least -Wall and -Wextra, for MSVC /W4) and treat them as errors you might even get a warning about using the uninitialized member variable.
I also suggest you make all member variables private.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Some programmer dude |
