I am puzzled by how to access a std::vector in a class with another a std::vector. A previous discussion(Why is it OK to return a 'vector' from a function?) deals with a similar issue, but it seems I must have misunderstood something.
Here is a sketch of my code:
class Employee
m_id;
public:
set_id(int id);
id();
In Employee.cpp
void Employee::set_id(const int id)
{
m_id = id; // m_id is 5
}
int Employee::id() const
{
return m_id; // m_id is rubbish
}
class Company
public:
std::vector<Employee> m_employees;
In Company.cpp
void Company::addEmployee(const addEmployee employee) // A vant to pass a copy of employee
{
m_employees.push_back(employee);
}
std::vector<Employee> Company::employees()
{
return m_employees;
}
in myClass.h
std::vector<Company> m_companies;
in myClass.cpp
int empl_id = 5; // test value
m_companyIndex = 0; // for test
m_emplIndex = 0; //
Company company;
Employee employee;
m_companies.push_back(company);
m_companies.at(m_companyIndex).addEmployee(employee);
m_companies.at(m_companyIndex).employees().at(m_emplIndex).set_id(empl_id);
int idRet = m_companies.at(m_companyIndex).employees().at(m_emplIndex).id();
idRet contans an apparently random number, instead of 5. Using a debugger shos that
If I instantiate Employee in myClass I can set and read back m_id; idem for Company, so the problem seems to be realted to std::vector m_employees; in class Company. Could it have something to do with "Return Value Optimisation"? By the way, I am using gcc 7.5.4.