When showing the sample “triangle” function on Slide 12, ask the students if they can spot any other
function on the page. The other function is called main and, except for its name, is an ordinary function.
Single-step through the “triangle” program on Slide 12 and relate each of the actions to the items listed
in Slide 13. C++ does a lot behind people’s back, so get the students used to the idea that the compiler
does all sort of things that are not obvious from the code.
You might want to point out that other languages have functions (which return values) and subroutines
or procedures (which do not). C++ makes a single “function” syntax do the work of both.
Call by Value Demonstration
The general idea is to have the members of the class execute by hand a simple program to compute the
area of a rectangle. Assign one student the job of funct function. This “code” is:
void funct(int j) {
j++;
}
Page 28
Have the student write down his code on the right side of the board.
Another student is given the job of main. His code is:
int main()
{
int my_j = 20;
func(j);
cout << “my_j is “ << my_j<< ‘
’;
return (0);
}
The main student hand executes his code. When he comes to the funct call he should write 20 on a
slip of paper and pass it to the funct student.
Point out that the information is passed one way from main to funct. Once the funct student gets
the note, he can do anything with it. He can alter the values, eat it, anything. The only thing he can’t do
with it is pass it back to the main student.
Reference Values
Set up the main and funct students as before. The area student’s code is now:
int area(int &j) {
j++;
}
With references the parameter passing is different. Have the main student create two boxes labeled
my_width and my_height in the middle of the board. The labels should be on the left toward the
main side of the board.
When the call is made, the area student puts the labels width and height on the right side of the
boxes. This means that each box will have two names. There is only one box.
It should be noted that if the function funct changes anything in the box, the change will be reflected
in the main program. That’s because there is only one box with two labels.
The process of adding a label j to the box already labeled my_j is called binding and is automatically
performed by C++ during a function call.
Practical C++ Programming by manish baranwal
Start from the beginning
