Is it possible to pass an object from one function to another ─ justify from an example.

Passing Objects: An object can be used as a function argument in the following two ways,

  1. pass-by-value
  2. pass-by-reference

Using the first option given above we pass the value of an object to a function where the value of the used object will not change, but only be used. Use of the second will change the object that will be used. For explanation considering the following example,


class friendshow{
    int a,b;
        void set_ab(int, int);
        friend int sum(friendshow);

void friendshow :: set_ab(int x, int y){

int sum(friendshow x){ //Line 1
    return x.a+x.b;

void main(){
    friendshow ob;       //Line 2
    ob.set_ab(5,7);      //Line 3
    cout<<sum(ob); //Line 4

Here in the Line 2 we can see that ob is an object of friendshow class type. Just in the next Line 3 we are setting the values of the variables a and b using its arguments. Now in the last Line 4 we are calling a function argument of which is ob. Thus its value is getting passed to the function of Line 1 and coming back after operation. So here we are passing object.

Google Recommends Recommends


Contact Us