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
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
see also: Learn Pointers in C++ Programming with Examples
Explanation of functions
Advantages
- When data is large it reduce the copies of data and creates less system overhead.
- 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;
}
Read also: C++ pointer example with pass by reference
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 comments:
Post a Comment