Differ pass by value and reference c++ example

Differ pass by value and reference c++ example
Di Posting Oleh : Simple Learning
Kategori : by cpp_tutorial example functions pass pointers reference value

Pass by value in C++ Programming
In this method we call a function by passing a value. A new copy of value is made and send to functions body. Where operations are applied on new copied value.




Advantages
  • New copy is made of value after passing so if changes go wrong the original data will be save
  • It increase the security of data
Disadvantage
  • If the data is huge making too much copies may cause system over head.

Pass by reference in C++ Programming
In this method we call a function by its reference using address operator. It don't make a copy of data and pass the address of value to the function. Where operations are applied on the reference of value and changes made permanently to data.

Advantages
  • When data is large it reduce the copies of data and creates less system overhead.
Disadvantage
  • Security of data can be weak because the real information is accessible and can be changed 


C++ function example of both ways pass by value and pass by reference
In this example there are two functions one calculates a cube of number with value and other calculates cube of number with reference. With value returns result and with reference not return result.

#include<iostream>
using namespace std;

int
pass_Value(int);
void
pass_reference(int &);
int
main()
{

int
num1,num2;

cout<<"Enter First Number: ";cin>>num1;
cout<<"Enter Second Number: ";cin>>num2;

cout<<"\n\n\n";

int
result=pass_Value(num1);
cout<<"\t\tPass By Value Result: "<<result<<endl;

pass_reference(num2);
cout<<"\t\tPass By Reference Result: "<<num2<<endl;

return
0;

}


int
pass_Value(int number)
{

return
(number*number*number);
}


void
pass_reference(int &number)
{

number=number*number*number;
}



Input Output Example:

see also: Learn Pointers in C++ Programming with Examples


Explanation of functions

  • First function is simple we received a value calculate its cube and return simply the new result.
  • In second function we applies changes using reference of number we sent so no need to return here. As changes are made permanently.



See More Examples Here: C++ Simple Examples

0 Response to "Differ pass by value and reference c++ example"

Post a Comment