|
||||||||
Exercise: Passing Parametersdue Jan 18C++ allows you to pass parameters in 3 ways: 1) by value, 2) by reference, 3)by constant reference. This exercise has 3 parts and will help you understand the difference. Show results of each part to your instructor.
Part 1: Pass by ValueWrite a C++ program named MyTestParam1 with a void function called doit(int x)that has one parameter of type int named x. This function should perform the following tasks in order:
The program MyTestParam should create a variable y and do the following in order:
What results do you see and why?
Part 2: Pass by ReferenceAlter the function so that it is a void function called doit(int &x). Run the program MyTestParam again and observe the differences. What results do you see and why?
Part 3: Pass by Const ReferenceAlter the function from part 1 so that it is a void function called doit(const int &x). Try to compile & run the program MyTestParam again and observe the differences. What happened and why? Try removing the x=x+1 line from the function and try to compile&run. What has happened now and why?
class Student {
public:
String Name;
int age;
int SSNum;
String Advisor;
void PrintInfo();
}
//now in Student.cpp file
void Student::PrintInfo(){
cout << "Name: " << Name << endl;
cout << "age: " << age << endl;
cout << "SS#: " << SSNum << endl;
cout << "Advisor: " << Advisor << endl;
}
|
||||||||
| © Lynne Grewe |