What have I done wrong when coding this array of objects in C++? -
i have 2 classes, personnellists , employee. create instance of personnellists in main, so:
int main() { personnellists example; //make personnel list ... } personnellists uses constructor member initialisation of list of employees, number of employees, , size of array:
personnellists::personnellists(): list(new employee[size]), numemployees(0), arraysize(size){ } this results in null empty employees being created (i think?):
employee::employee(): employeenumber(0), name(null), department(null) { } it @ line invalid null pointer error.
i new c++, fresh off boat java programming. i'm still novice pointers, i'm not quite sure i'm doing wrong here.
update: requested, here class definition of employee:
#include <iostream> class employee { public: employee(); //constructor employee(std::string name, std::string deparment); void print() const; //print employee's details void setemployeeno(int employeenum); private: int employeenumber; std::string name; std::string department; };
in java, new employee[size] creates array of null references.
in c++, new employee[size] creates array of default-constructed instances of employee. default constructor tries set name , department null. attempting initialize std::string null give error describe.
there's no "null" string in c++, default-construct name , department, set them empty strings:
employee::employee(): employeenumber(0), name(), department() { finally, if list can contain variable number of elements, recommend use std::vector<employee> (which similar arraylist<employee> in java).
Comments
Post a Comment