×

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++

Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have the same result. So the remaining statements are inevitable; when one is over the other significant? What are the causes we’re using one over another?

Passing by Pointer:

// C++ program for swaping two numbers with pass-by-pointer.
#include <iostream>
using namespace std;
void swap(int* t, int* p)
{
    int k = *t;
    *t = *p;
    *p = k;
}
int main()
{
    int s = 78, c = 55;
    cout << "Before Swap\n";
    cout << "s = " << s << " c = " << c << "\n";
    swap(&s, &c);
    cout << "After Swap with pass by pointer\n";
    cout << "s = " << s << " c = " << c << "\n";
}

Output:

Passing by Reference vs Pointer in C++

Passing by Reference:

// C++ program to swap two numbers using
// pass by reference.
#include <iostream>
using namespace std;
void swap(int& w, int& q)
{
    int l = w;
    w = q;
    q = l;
}
int main()
{
    int n = 122, m = 210;
    cout << "Before Swap\n";
    cout << "n = " << n << " m = " << m << "\n";
    swap(n, m);
    cout << "After Swap with pass by reference\n";
    cout << "n = " << n << " m = " << m << "\n";
}

Output:

Passing by Reference vs Pointer in C++

The difference in between Reference variable and pointer variable

  • Generally, references are applied with pointers. A reference is the same object; it only has to refer to an entity with a different name and context. They are safer to use as references cannot be NULL.
  • A pointer may be reassigned while the relation cannot be assigned and must only be allocated at initialization.
  • The pointer is explicitly assignable to NULL, while reference cannot.
  • Pointers may append over an array, and we can use + + to move towards the next object a pointer points toward.
  • The variable is a way that has an address to the memory. A reference has the same address as the object it is referring to.
  • A class or struct pointer requires' ->'(arrow operator) to reach its members while a reference uses a. '(dot operator)
  • To access the memory location it refers to, a pointer must be dereferenced with *, while a pointer can be substituted directly.
// C++ program to display variations between reference and pointer.
#include <iostream>
using namespace std;
struct demo
{
    int s;
};
int main()
{
    int m = 3;
    int n = 8;
    demo d;
    int *k;
    k =  &m;
    k = &n;                     // 1. Pointer reintialization allowed
    int &t = m;
    // &r = y;                  // 1. Compile Error
    t = n;                      // 1. m value becomes 3
    k = NULL;           
    // &r = NULL;               // 2. Compile Error
    k++;                        // 3. Points to next memory location
    t++;                        // 3. m values becomes 8
    cout << &k << " " << &m << endl;    // 4. Different address
    cout << &t << " " << &m << endl;    // 4. Same address
    demo *q = &d;
    demo &qq = d;
    q->s = 9;
    // q.s = 9;                 // 5. Compile Error 
    qq.s = 9;
    // qq->s = 9;               // 5. Compile Error
    cout << k << endl;       
    cout << t << endl;            
    return 0;
}

Output:

Passing by Reference vs Pointer in C++

Related Topics

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

7 minutes read.

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows...

5 minutes read.

Dynamic _Cast in C++

C++ is one of the most powerful programming languages. We can write object-oriented and structured programming with the help of C++. In this article, we will learn about the dynamic...

3 minutes read.

Program that produces different results in C and C++

Introduction: There are many such programs that compile run both in C and C++ but give different outcomes when compiled by the C and C++ compilers. There are a variety of such...

6 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

C++ Aggregation

C++ Aggregation Definition: In C++, aggregation is a process in which one class (as an entity reference) defines another class. It provides another way to reuse the class. It represents...

4 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

C++ Scope of Variables

In this tutorial, we will explore about the scope of variables in c++ programming language. And also, how it works in a program. What is Scope? The range of applications for something...

4 minutes read.

Backtracking Time Complexity in C++

Introduction to Backtracking Backtracking is an important part of programming languages, and with the help of backtracking, we can do many operations in an advanced data structure. For doing major operations,...

4 minutes read.

C++ Virtual Destructor

In C++, a destructor is a class member function that is used to free up space or remove an object of the class that has gone out of scope. The...

4 minutes read.

C++ Iterators

What are iterators ? Iterators are among the four foundations of the C++ Standard Template Library, also known as the STL. The memory address of the STL container classes is pointed...

15 minutes read.

sort() function in C++

This tutorial covers the various built-in sort functions found in the C++ algorithm’s library.  What Does C++ Sort Mean? The concept of sorting in C++ entails rearranging an array's elements in a...

3 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

How to create a table in C++

C++ is a programming language that has evolved as an improvement of c language. It includes an object-oriented archetype. C++ programming language is a compiled language that complies with the...

3 minutes read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

Singleton Design Pattern in C++

Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton...

2 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.