Skip to main content

Difference between pass by value , pass by pointer and pass by reference in c++ (really important)

so working with javascript can be quite different than working with c++. As c++ has pointer concept which is really unique and sometime really hard to understand in many c++ project for example games where you need to pass variable from one class to other or pass a variable from one function to other.

i am mainly from javascript background where simple data types like number and string pass by value and complex data types like object and array passed by reference.


but in c++ variables passed by three way and these are really important when u are dealing in heap or stack memory.

1. Pass By Value  (copy value)

we hardly used this so check out my example i have a class called 

class Demon
{
    private:
        int age;
    public:
        Demon(){};
        ~Demon(){};
        void setAge(int __age)
        {
            age=__age;
        };
        int getAge()
        {
          return age;  
        }
       
};

where i have a age function which is public method now inside my

int main i am creating a new instance of Demon(d3 in my case).
and passing that instance to a function passByValue

   //pass by value
void passByValue(Demon p)
{
    p.setAge(44);
}

int main()
{

    //pass by value
     Demon d2;
    d2.setAge(22);
    cout <<"----->this is d....." <<d2.getAge() << endl;
    passByValue(d2);
    cout <<"----->this is d...." <<d2.getAge() <<  endl<<endl;;
}

after setting age value to 44 i am still getting same age value even i changed it inside passByValue function the reason is that i am passing variable by value so passByValue and my main function contain different variable or you can say passByValue contain a copy of Demon instance 

so this case hardly used when u create a real c++ programme.

 
2. Pass by pointer (move value)

    this is one of most used method passing variables between classes and function

    check out the code:-

    using same class i am passing variable as a pointer

    void passPointer(Demon *p)
    {
         p->setAge(44);
    }; 
    
    int main()
    {

    Demon *d=new Demon();
    d->setAge(22);
    cout <<"----->this is d....." <<d->getAge() << endl;
    passPointer(d);
    cout <<"----->this is d...." <<d->getAge() << endl<<endl;
   }

if you run the above code you would get age value changed in main function.

Reason is very simple passing pointer across function or classes shared same memory address so if you change one than other would also changed. just try to get memory location of pointer inside  passPointer and main you would get same memory address.



3. last one is pass by reference
    
    
    Last one is passed by reference in this method we passed variable by reference like below

//pass by reference
void passbyReference(Demon &p)
{
    p.setAge(44);
}

inside main i would write my code like below

    int main()
 {
     Demon d3;
    d3.setAge(22);
    cout <<"----->this is d....." <<d3.getAge() << endl;
    passbyReference(d3);
    cout <<"----->this is d...." <<d3.getAge() << endl<<endl;;
 }

in pass by reference we target the same memory so Demon instance age would be a new value.
    
if you closely look passbyReference 

you can check that is contain & sign that how we hint compiler that this value is passed by reference 


Now main question where we should used to which one

1. passed by value hardly used but you can used it where data type is small like int so copy can't make that much difference but most of cases you should avoid it.


2. pass by reference is used when you want manipulate same variable by different classes but wants only a single instance like a scoreboard which contain a model class and where you want same values like score, player name etc same across multiple screens. 

some example 

addTexture(string &textureName) so you don't need a copy of textureName u can just passed it as a reference.

3. passed by pointer is most useful when u need to store heavy data in computer memory because pointer always stores in heap rather than stack for example a texture or a game screen or button or widgets.


Last Point never used pass by value always used pass by reference or pass by pointer.




 
 
    











Comments

Popular posts from this blog

Creating a word Scramble game where you can drag and drop the word and create a complete word. (drag and drop word Scramble game).

Creating a word game using  phaser game engine which is a javascript based gaming engine  where u can drag and drop world like Word Scramble Game and complete a given word. your index.html file look like below < html > < head > < script src = "src/phaser.min.js" ></ script > < script src = "src/wordGame.js" ></ script > < script src = "src/main.js" ></ script > </ head > < body > </ body > </ html > 1.    <script src="src/phaser.min.js"></script> required to run the  phaser game engine. 2. rest of the two files deals with game logics      <script src="src/wordGame.js"></script>       <script src="src/main.js"></script> you can download whole project from https://github.com/manishchauhan/wordgame/tree/master just copy and paste the project in your local server and run ...

starting with three.js and react with a very simple example

 1. three.js is undoubtedly the best library to create interactive content for the web in 3d. link https://threejs.org/ a working sample of three with react can be found below https://stackblitz.com/edit/react-7n5qf9?file=src%2FApp.js why choose threejs 1. lightweight  2.fast 3.big community  https://discourse.threejs.org/ 4. even you can use unity or unreal to publish html5 content but i don't think that would be acceptable in many cases. 5. open-source project. i created a running sample with React  https://stackblitz.com/edit/react-7n5qf9?file=src%2FApp.js

A simple binary search tree with generic approach tree can store any type of data. (DFS and BFS)

 1. a binary search tree in c++ using a generic approach with both BFS and DFS approach    working tree    https://www.onlinegdb.com/edit/HkuQLdA-w code=> some properties of binary search tree-> 1. binary search tree is not always a balanced tree.  2. Inorder, traversing gives you sorted data.  3.  best is o(log n) and worst is O(n).  4. left node data is always less than root data and right node data always be greater than root data.  5. red-black tree STL map is a balanced binary search tree. *******************************************************************************/ #include <stdio.h> #include<iostream> #include<queue> using namespace std; template < typename T > class Node {   //can store any type of data private:   //genric data or store any type of data   T data;   //reference of left pointer   Node *left = nullptr;   //reference of right pointer   Node *rig...