//******************************************************* // We introduce the concept of pass by referance // The difference between a method which is //implemented by using pass by referance and which is not //******************************************************* #include <cstdlib> #include <iostream> using namespace std; //Defining a method which calculates the square of given number int getSquare1(int num1); int getSquare2(int &num2); int main(int argc, char *argv[]) { // We define two integer for our two different getSquare method int num1 = 2,num2 = 2; cout<<"num1 was initially "<<num1<<endl; cout<<"num2 was initially "<<num2<<endl; // We call the methods cout<<"Square of num1 is "<<getSquare1(num1)<<endl; cout<<"Square of num2 is "<<getSquare2(num2)<<endl; //After calling square methods cout<<"num1 is "<<num1<<endl; cout<<"num2 is "<<num2<<endl; system("PAUSE"); return EXIT_SUCCESS; } int getSquare1(int num1){ num1 = num1*num1; return num1; } int getSquare2(int &num2){ num2 = num2*num2; return num2; } //************************************************************ //The difference between the methods is that the first one do not //use the variable it creates a variable instead of the num1 but //the second method it uses the num2 since we send adress of the //variable to the method so it uses num2 not creates a copy of num2. //Thus, num2 changes. //**************************************************************
Output:
