
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to pass objects to functions in C++?
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);
- Related Articles
- How to pass objects to functions in C++ Program?
- How to pass arguments to anonymous functions in JavaScript?
- How to pass event objects from one function to another in JavaScript?
- How to pass parameters to a method in C#?
- How to pass pointers as parameters to methods in C#?
- How do you pass objects by reference in PHP 5?
- How to pass an array by reference in C++
- How arrays are passed to functions in C/C++
- Are Python functions objects?
- How exactly do Python functions return/yield objects?
- Can we pass objects as an argument in Java?
- How to pass parameters using param array in a C# method?
- How to pass a 2D array as a parameter in C?
- How to call C++ functions from Java?
- How to pass entire structure as an argument to function in C language?
