My apologies for the bad title, I'm self-taught c++ newbie.
I'd coding the usual example of a Company class along with Employess class and Person class.
Basically my code should create a company, add employees to that and print the full list of employees.
Here's a short version of what I did. It looks quite long, but the isse is just in a couple of lines. All the others are fine, but I needed them so to make the code work.
// g++ test.cpp -o exe.x && ./exe.x
#include <iostream>
#include <vector>
class Person {
private:
std::string name;
std::string surname;
public:
Person() {};
Person(const std::string n, const std::string m) : name(n), surname(m) {}
~Person() {};
friend std::ostream & operator<<(std::ostream & os, const Person & person) {
return os << person.name << " " << person.surname;
}
};
class Employee: public Person {
private:
size_t salary;
public:
Employee(const Person p, const size_t w) {
salary = w;
}
~Employee() {};
friend std::ostream & operator<<(std::ostream & os, const Employee & employee) {
std::cout << employee; // this should call std::cout from Person
return os << ", " << employee.salary; // this should also print the salary as additional info
}
};
class Company {
private:
std::string companyName;
size_t maxNumberEmployees;
std::vector<Employee> employees;
public:
Company(const std::string n, const size_t p) {
companyName = n;
maxNumberEmployees = p;
}
~Company() {
employees.clear();
}
void addEmployee(const Employee employee) {
if (employees.size() < maxNumberEmployees) {
employees.push_back(employee);
}
return;
}
void listEmployees() const {
for (Employee employee : employees) {
std::cout << employee << std::endl;
}
return;
}
};
int main ( int argc, char* argv[] ) {
Company com("CompanyName", 15);
Person per("Name1", "Surname1");
Employee imp(per, 2000);
com.addEmployee(imp);
com.listEmployees();
return 0;
}
Employee
is a sub-class of Person
. In the latter, I defined how the std::cout
command should print an object of type Person
.
When I give std::cout
for an Employee
object, I want my code to call the std::cout
of the Person
class, with an additional info defined in the Employee
class.
I put two comments in the lines in which I have these troubles. The code gets stuck if I run it this way. There's definetely something wrong in that std::cout << employee
, like if it were a recursive function. But I don't know how to fix that in the way I want it.