0

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.

2
  • 4
    Please please please read a BOOK. Commented Jan 22, 2011 at 12:49
  • This was written in another place in the articel: "...we needed to pass the struct itself to the SetDate() function as the first parameter. Otherwise, SetDate() wouldn’t know what DateStruct we wanted to work on.". Commented Jan 22, 2011 at 13:01

3 Answers 3

4

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;
Sign up to request clarification or add additional context in comments.

Comments

3

It means a reference to an existing DateStruct instance.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.