In Deitel C++ book (“C++11 for Programmers”, p.286) , there is an example of:
class Date { ... }
class Employee {
public:
Employee(const string &, const string &, const Date &, const Date &);
private:
string firstName;
string lastName;
const Date birthDate;
const Date hireDate;
}
Employee::Employee( const string &first, const string &last,
const Date &dateOfBirth, const Data &dateOfHire)
: firstName( first),
lastName( last),
birthDate(dateOfBirth),
hireDate(dateOfHire) { };
The book says the member initializer such as birthDate(dateOfBirth) invoked Date class’s copy constructor. I am confused as to why copy constructor? I thought the whole point of “pass by reference” is to avoid the object copy?
If I do:
Date birth(7,24, 1959);
Date hire(2,12, 1988);
Employer staff("bob", "blue", birth, hire);
How many Date objects does the system have now, 2 or 4? (Two created at the start, two are created by copy constructor)
It is not the passing mode that involves a copy.
It is the initialization of the members that involve a copy (obviously? the parameters don’t live in the class, and the class members need to get the same value: copy)
Let’s examine
Employee::Employee, passingfnamebyconst&(no copy).std::string(const std::string&), again passing the parameter on byconst&(still no copy).std::stringcopy constructor now takes all necessary steps to copy the the value of it’s parameter into the object itself. This is the copyIt makes sense that when you construct a new
std::string(in this case as a member of Employee), it results in a … newstd::string. Thinking of it this way makes it very easy to grasp, I think.