How to pass objects to functions in C++ Program?


There are four ways of passing objects to functions. Let's assume you have a class X and want to pass it to a function fun, then

Pass by Value

This creates a shallow local copy of the object in the function scope. Things you modify here won't be reflected in the object passed to it. For example,

Declaration

void fun(X x);

Calling

X x;
fun(x);

Pass by Reference

This passes a reference to the object to the function. Things you modify here will be reflected in the object passed to it. No copy of the object is created. For example,

Declaration

void fun(X &x);

Calling

X x;
fun(x);

Pass by const Reference

This passes a const reference to the object to the function. You cannot modify/reassign the object here directly(you can use its methods that do so though). This is useful if you want the function to have only a readonly copy of the object. No copy of the object is created. For example,

Declaration

void fun(X const *x);

Calling

X x;
fun(&x);

Pass by const Pointer

This passes a const pointer to the object to the function. You cannot modify/reassign the pointer here. This is useful if you want the function to have only the address of this object in the pointer. No copy of object is created. For example,

Declaration

void fun(X *x);

Calling

X x;
fun(&x);

Pass by Pointer

This passes a pointer to the object to the function. This is similar to passing a reference to the object. No copy of object is created. For example,

Declaration

<void fun(X *x);>

Calling

X x;
fun(&x);

Updated on: 30-Jul-2019

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements