You have incorrectly defined a copy constructor, a copy assignment operator, and a destructor.
For example, the copy constructor must copy a string, and not just assign one pointer to another. The assignment copy statement must first delete the current name_ pointer before allocating a new memory. And the destructor should release the allocated memory.
Below is a demonstration program that shows how they can be defined. In addition, the copyString function should be declared as static and private.
#include <iostream> #include <list> #include <string> #include <cstring> class Employee { private: char *name_; private: static void copyString( char **dest, const char *source ) { *dest = new char[ std::strlen( source ) + 1 ]; strcpy( *dest, source ); } public: Employee( const char *name ) : name_( nullptr ) { copyString( &name_, name ); } Employee( const Employee © ) : name_( nullptr ) { copyString( &name_, copy.name_ ); } Employee() { delete [] name_; } Employee & operator =( const Employee © ) { if ( this != © ) { delete [] name_; name_ = nullptr; copyString( &name_, copy.name_ ); } return *this; } friend std::ostream &operator <<( std::ostream &out, const Employee &employee ) { return out << employee.name_; } }; class Company { public: Company( const std::string &name ) : name( name ) {}; virtual ~Company() = default; void hire( const Employee &employee ) { employees.push_back( employee ); } friend std::ostream & operator <<( std::ostream &out, const Company &company ); private: std::string name; typedef std::list<Employee> EmployeeList; EmployeeList employees; }; std::ostream & operator <<( std::ostream &out, const Company &company ) { out << company.name << "(" << company.employees.size() << "): "; for ( const auto &employee : company.employees ) { out << "\"" << employee << "\" "; } out << std::endl; return out; } void addStuff( Company &company ) { company.hire( Employee( "Max Mustermann" ) ); company.hire( Employee( "Erika Musterfrau" ) ); } int main() { Company company( "OwesomeCo" ); addStuff( company ); std::cout << company; return 0; }
Output of the program to the console
OwesomeCo(2): "Max Mustermann" "Erika Musterfrau"
If you wish, you can also add a relocation constructor and an assignment operator to the Employee class. For example,
Employee( Employee &© ) : name_( nullptr ) { std::swap( name_, copy.name_ ); } Employee & operator =( Employee &© ) { if ( this != © ) { std::swap( name_, copy.name_ ); } return *this; }