- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Are there benefits of passing by pointer over passing by reference in C++?
A pointer can receive a null parameter whereas a reference can’t. You can only use pointer if you want to pass “no object”.
Explicitly passing by pointer allow us to see the whether the object is passes by reference or value at call site.
These are simple example of passing by pointer and passing by reference −
Passing by pointer
Example
#include <iostream> using namespace std; void swap(int* a, int* b) { int c = *a; *a= *b; *b = c; } int main() { int m =7 , n = 6; cout << "Before Swap\n"; cout << "m = " << m << " n = " << n << "\n"; swap(&m, &n); cout << "After Swap by pass by pointer\n"; cout << "m = " << m << " n = " << n << "\n"; }
Output
Before Swap m = 7 n = 6 After Swap by pass by pointer m = 6 n = 7
Passing by reference
Example
#include <iostream> using namespace std; void swap(int& a, int& b) { int c = a; a= b; b = c; } int main() { int m =7 , n = 6; cout << "Before Swap\n"; cout << "m = " << m << " n = " << n << "\n"; swap(m, n); cout << "After Swap by pass by reference\n"; cout << "m = " << m << " n = " << n << "\n"; }
Output
Before Swap m = 7 n = 6 After Swap by pass by reference m = 6 n = 7
Advertisements