Hello,
I am coming from C and I understand pointers well enough. But I am having trouble understanding references.
I have created this simple class.
Code:
namespace emp_system
{
struct EMP_DETAILS
{
int empID;
std::string name;
};
class Employee
{
public:
Employee()
{
_emp_details = new EMP_DETAILS;
}
EMP_DETAILS& emp_details();
private:
EMP_DETAILS *_emp_details;
};
inline
EMP_DETAILS& Employee::emp_details()
{
return *_emp_details;
}
} // emp_system
And I am using it like this in my main.cpp:
Code:
using namespace emp_system;
Employee *emp = new Employee;
emp->emp_details().empID = 10102;
std::cout << "Emp ID: " << emp->emp_details().empID << std::endl;
However, I have some questions about this design.
1) should the struct be part of the class and not outside it. Any benefit to having it this way?
2) I am not sure I totally understand what I am returning from emp_details. I think it is a reference. Which would be the address of the struct object that is created in the constructor?
However, this line I think is de-referencing the pointer to get the value.
Code:
return *_emp_details;
However, as I am return the address of (&) would I not need to de-reference and return the pointer instead?
Code:
return _emp_details;
Many thanks,