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

Better Memory management with PixiJS or How to manage cpu and cpu memory in PixiJS.

PixiJS is my favorite framework when i am looking for a web games specially for mobile or desktop  PixiJS is fast blazing fast and you can get a decent FPS even on older device.   so here is my optimization techniques for PixiJs 1. manage your sprites in a better way use spritesheet to reduce the draw calls create big sprite sheet which contain multiple sprites can be draw in gpu with a single draw call. use TexturePacker  https://www.codeandweb.com/texturepacker  best tool when its comes to spritesheet 2. for floating point calculation round off calculation for example let  speed = 0.75 ; let  position = 100 ; console . log ( Math . round ( speed * position )) 3. don't create very big canvas when u need a big canvas size game just try to create a small canvas and translate it. 4. its very important one managing TextureCache in memory you can get all TextureCache list by using  Object.entries(PIXI.utils.TextureCache); so even you use ap...

adding particles Effect in pixijs using https://pixijs.io/pixi-particles-editor/

adding particle in pixijs is very easy using the below tool more information can be found below https://github.com/pixijs/pixi-particles https://pixijs.io/pixi-particles-editor/ required packages  /// < reference path = "node_modules/pixi-particles/ambient.d.ts" /> import 'pixi-particles' code of particle delcare a     global variable   private emitter ?: Emitter ; const img = PIXI . Texture . from ( "./assets/images/particle.png" ); this . emitter = new Emitter ( this ,[ img ],{ "alpha" : { "start" : 0.62 , "end" : 0.39 }, "scale" : { "start" : 0.1 , "end" : 0.9 , "minimumScaleMultiplier" : 1.25 }, "color" : { "start" : "#ffff8f" , "end" : ...