Showing posts with label call by value. Show all posts
Showing posts with label call by value. Show all posts

20130411

How to distinguish between call by value, call by reference, call by address

/*How to distinguish between call by value, call by reference, call by address.
Program to distinguish between pass by value,pass by reference,pass by address. Call by reference and call by address affects the calling value while call by value doe not. Most important difference is that in call by value new object is created which is some times such as when size of the variable is too large is not desirable so call by reference is preferred over call by value*/

#include<stdio.h>
#include<iostream>
using namespace std;
void callbyreference(int * x);//pass by address
int main()
{
int x;
x=10;
printf("Before x=%d",x);//10
callbyvalue(&x);
printf("\nAfter x=%d",x);//15
printf("\n");
return 0;
}

void callbyreference(int * x)
{
*x=*x+5;//mind the*
}


//CALL BY REFERNCE, PASS BY REFERNCE
/*

20120728

Is it necessary to accept an object by reference in copy constructor?

Is it necessary to accept a reference in copy constructor?
Yes, It is necessary to accept an object by reference in copy constructor because if an object is accepted by value then the copy constructor will fall in recursive loop.
C++ program for copy constructor:

#include<iostream>
using namespace std;
class copyDemo
{
int x;
public:
       copyDemo(copyDemo v) //taking object as value
        {
         x=v.x;
        }
};

int main()
{
copyDemo c;
copyDemo c1(c);// this will invoke copy constructor
return 0;
}

//explanation

The statement copyDemo c1(c);  causes the copy constructor to get called.
The value of c is passed If the copy constructor collects c in v by value then
the statement  copyDemo v would become as
copyDemo v=c;
here v is getting created and initialized so again copy constructor will get called and will go in recursive call loop.
Previous                             Home                               Next