How to pass objects to functions in C++?

C++Server Side ProgrammingProgramming

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 const *x);

Calling

X x;
fun(&x);

Pass by const 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);
raja
Published on 28-Feb-2018 09:34:57
Advertisements