Reputation: 48986
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/
It has the following code:
// Declare a DateStruct variable
DateStruct sToday;
// Initialize it manually
sToday.nMonth = 10;
sToday.nDay = 14;
sToday.nYear = 2020;
// Here is a function to initialize a date
void SetDate(DateStruct &sDate, int nMonth, int nDay, int Year)
{
sDate.nMonth = nMonth;
sDate.nDay = nDay;
sDate.nYear = nYear;
}
// Init our date to the same date using the function
SetDate(sToday, 10, 14, 2020);
What is the purpose of the
DateStruct &sDate
parameter in the function signature, especially that I cannot see a use of it in the function body?
Thanks.
Upvotes: 0
Views: 1736
Reputation: 69575
The aforementioned, highlighted code is called a reference. You might think of references as aliases for variables.
During function call sDate
becomes an alias to sToday
- which has been given as a parameter. Thus it makes it possible to modify sToday
from within the function!
The reason is that it makes possible to give complex structures that might be filled up with data, modified, etc. inside of called functions.
In your case the SetDate
function takes separate year, month and day - and packs it inside sDate
(== sToday
) structure.
Just compare the first way of initialization (you need to mention all struct members yourself) to calling SetDate
function.
eg.:
DateStruct janFirst;
DateStruct decLast;
SetDate(janFirst, 1, 1, 2011);
SetDate(decLast, 12, 31, 2011);
Compare this to how much code would have been written if you had to fill all those janFirst
, decLast
structures by hand!
Upvotes: 0
Reputation: 13129
It means it will take as a first argument a reference to a DateStruct and that this reference will be called sDate in the function's body. The sDate reference is then used in each lines of the body:
sDate.nMonth = nMonth;
sDate.nDay = nDay;
sDate.nYear = nYear;
Upvotes: 4