What is the Difference Between a Pointer and a Reference C++

Поделиться
HTML-код
  • Опубликовано: 5 янв 2025

Комментарии •

  • @systemofapwne
    @systemofapwne 2 года назад +323

    In short: Pointers and references can be used to refer to data in memory, without copying the data to a new variable. That is efficient. While pointers can arbitrarily be changed to point to any memory addresses and need a dereferentiation in order to read the value, references do refer to a fixed location in memory and behave like normal variables (do not need dereferentiation), when one wants to read their value. However, since no data is copied from one var to another in either case, changes made to these memory locations will be present instantly for pointers and references.

    • @VampyrumFerox
      @VampyrumFerox 2 года назад +52

      Nice explanation, but next time could you drag that out into a 3 hour video? I get paid by the hour. Thanks.

    • @Singularitarian
      @Singularitarian 2 года назад +9

      What’s the reason for the language to have references at all? Why not just pointers? It doesn’t seem like references can do anything we couldn’t already do with pointers.

    • @AxeMask
      @AxeMask 2 года назад +6

      @@Singularitarian I'm relatively new to C++ and pointers / references so my answer could be wrong but I had the same question after watching the video initially. However, upon further thought, I don't think that references are used in the way that the video demonstrated. I think the main use case is to use a reference value as the formal parameter of a function so that when you're passing large values to a function, you aren't compromising performance by copying the entire value; hence the terms 'pass by value' vs. 'pass by reference'.
      That being said, I could also be completely wrong so if anyone sees this and can clarify for us, that would be greatly appreciated. Cheers!

    • @Odb718
      @Odb718 2 года назад +4

      @@Singularitarian I think sometimes you have to "decode" a variable and pointers may not have to go through that to work in an equation. It might make a cheap way to have a "global variable" by making a ref to it. It's probably a read only type situation. I'm not sure lol that's why I watched this video....

    • @anonym3852
      @anonym3852 2 года назад +19

      @@AxeMask Pointers are not in every programming language. Take PHP as an example, they only work with references.
      The key differences with an example:
      A pointer is a variable, that points to the address of another variable, but it CAN be changed, CAN be NULL AND you can dereference it, so you can access the memory itself or the address to it.
      A reference is a variable, that points to the address of another variable, but it CANT be changed and CANT be NULL.
      Lets say you have a function which always expect a User object. Than you dont want a pointer. A pointer could be NULL, so your function cant work and there will be errors if it is NULL. You could check before, if its not NULL, but this costs additional ressources. Also someone could change the value where the pointer is pointing too within their memory. This can be unexpected behavior.
      Better would be a reference in that case. You can be sure with references, that they have a valid value of the specific type (in this example a User object).
      Also for some styleguide if there is a &foo parameter in your function(if not const), you can assume it will probably get changed.
      Lets say you have an array with object. (Dont mind me if the syntax is not completly right, havent used C++ in a while, i try to make it at least somehow clear what i try to do and fk styleguides on yt)
      public function getTheHighestNumber(&numbers)
      {
      *highestNumber = numbers[0]; //Get first number of numbers array
      count = size(numbers);
      for(i = 1; i

  • @5r1zan
    @5r1zan 8 лет назад +729

    Liked the idea of split screen.... helps visualising the code.... awesome concept....

  • @terrymoist
    @terrymoist 4 года назад +309

    I can't understate how easy and simple you made this to understand, very epic.

    • @Timo-Epis
      @Timo-Epis Год назад

      These nerds try to act like they have an IQ of 300 by explaining things in a difficult way.

    • @carlpeterkirkebo2036
      @carlpeterkirkebo2036 Год назад +1

      Totally agree!

  • @bestredditstories1158
    @bestredditstories1158 2 года назад +4

    I can't believe a seven-minute video summed up a concept that I did not understand for the longest time. Thank you so much for this.

  • @blackblocky3866
    @blackblocky3866 Год назад +4

    Literally the best explanation of the pointers in all of coding history.

  • @facts-nuk
    @facts-nuk 4 года назад +17

    It's been four year by now but still it is precious. This video make my day.

  • @Adam-gj3dn
    @Adam-gj3dn 4 года назад +5

    Definitely the best video on RUclips explaining the difference between pointers and references. Also, thank you for not using all the programming jargon when explaining. Thank you!

  • @FirezFlightz
    @FirezFlightz 4 года назад +13

    I know this is 3 years later but, this is the best most understandable pointer video ive ever seen ! Thank you for making it!

  • @Squash101
    @Squash101 5 месяцев назад

    Hands down the absolute best video on pointers I've even seen! I'm excited to watch your videos on LL and the rest of the different types of DS.

  • @Proroker365
    @Proroker365 2 месяца назад

    At last, after years, I finally understand how pointers and references works. 🤯
    Thank you very much for the explanation with visualizing the code itself! 😁👍

  • @arpeggio1231
    @arpeggio1231 2 года назад

    bro so easy and simple explanation, I got a friend who has 35 years in programming and he didn't make it easy to understand. Thanks again brother

  • @griffinloiselle2239
    @griffinloiselle2239 3 месяца назад

    This was the best explanation on both pointers and references I've found anywhere. Thank you!

  • @dilute6980
    @dilute6980 2 года назад +42

    1 small thing you didnt mention is that pointers also have their own memory address. Just like any variable calling operator & on a pointer returns the address of the pointer, which is different to the value of the pointer, being a memory address that it is pointing to

  • @alcurb
    @alcurb 6 лет назад +15

    Great explanation. Simple and concise.
    I've been taking a Lynda course C++ Essential Training by Bill Weinman but he blows through the explanation leaving me in the dust. I could see the results of what was happening in his code example, but it lacked the graphical elements that would help me understand. You did that, and it is now clear. Thanks.

  • @lachlanvanderdrift7013
    @lachlanvanderdrift7013 3 года назад +1

    bro, you made this so easy to understand. you're such a genius, I cant wait to come back to this channel for more things like this when I need it. keep it up

  • @ncpurge789
    @ncpurge789 4 года назад

    THIS IS THE BEST VIDEO I'VE EVER SEEN FOR EXPLAINING POINTERS AND REFERENCES I CAN'T THANK YOU ENOUGH.

  • @XxMonkeyACCxX
    @XxMonkeyACCxX 2 года назад

    i really appreciate writing the code while explaining the concept. I struggle understanding this concept with just drawings alone and then carrying it over to my projects. thank you

  • @MoodyDood
    @MoodyDood Год назад +2

    I suffered with pointers and references for close to a year, thanks a ton!

  • @FiicticioID
    @FiicticioID 2 года назад

    having c++ classes for 4 months, and i never had such a simple explanation between reference and pointers

  • @CarsonCameronClark
    @CarsonCameronClark 5 лет назад +31

    Most flawless explination I've ever seen of any programming concept. Well done and thank you.

  • @iVuDang
    @iVuDang Год назад

    love the visualization, conciseness, and easy to follow style of this video , thank you

  • @rpersen
    @rpersen 2 года назад

    Great explanation. Remember I struggled with this 20 years ago. Subbed.

  • @jonathanp5195
    @jonathanp5195 2 года назад +10

    I'm amazed by how elegantly you explained this. Thank you for being such a great instructor!

  • @o2dyt
    @o2dyt 6 лет назад

    My GF has a test tomorrow about this. You just helped me make it clearer for her. Thanks!

  • @auntikjeb6600
    @auntikjeb6600 Год назад

    You explained it so well i tried to understand the difference the whole day. Thank you🎉

  • @deivid-01
    @deivid-01 3 месяца назад

    I DON'T KNOW YOU, BUT I LOVE YOU. Thanks a lot man! Visualising the code helped a lot!

  • @sd9302
    @sd9302 2 года назад +1

    Wow! Can't express my gratitude in words! Thanks sir

  • @SFV4
    @SFV4 7 дней назад

    7:20: another big difference is that a pointer can hold the value nullptr to express it doesn’t point to anything.
    A reference always refers to an address and can’t be changed.
    This latter is the reason for the existence of std::reference_wrapper.
    When using a reference wrapper, you can change to what you are referring to

  • @weiqianzhang981
    @weiqianzhang981 Год назад

    by far the clearest video I've found.

  • @hishamakmal2149
    @hishamakmal2149 3 года назад

    This is by far the best explanation on this topic. Thanks a million Paul!

  • @Cagruntas
    @Cagruntas 8 лет назад +60

    Damn been looking for a good video on pointers for a while

  • @iyobosajefferson6457
    @iyobosajefferson6457 2 года назад

    Love how this was concise and diagrammatically explained.

  • @qemmm11
    @qemmm11 Год назад

    Suddenly! I feel that the pointer arithmetic is so easy😮
    Thanks❤

  • @anastasijad4830
    @anastasijad4830 2 года назад

    beautifully explained.. i got goosebumps when i finally figured it out

  • @taki-eddinechih5197
    @taki-eddinechih5197 11 месяцев назад

    the best explanation I've ever seen about pointers

  • @cauhxmilloy7670
    @cauhxmilloy7670 2 года назад +2

    Slight correction, pointers and references are really the same thing only differing slightly with syntax. You could liken a reference to a pointer that is never null and can only be set once (when declared). There are surely some syntax differences when working with pointers (no need to dereference, dot operator instead of arrow, etc), but they are really doing the same thing otherwise. You can verify by messing around with godbolt (looking at disassembly). Also note that you can do polymorphism with references.
    Thanks for the C++ content! The world needs more C++ enthusiasts! :)

  • @KaustavMajumder
    @KaustavMajumder 11 месяцев назад +1

    7:21 - The main essence of the video. However, I would recommend everyone to watch the entire video from start till end without skipping.

  • @Florakinz
    @Florakinz 6 лет назад +1

    Best video on the basics of pointers and reference. Period. :)

  • @JacobMartin-l1f
    @JacobMartin-l1f 2 года назад

    This is the most excellent explanation video one can imagine

  • @nasser3780
    @nasser3780 2 года назад +1

    you can not declare a reference without assignment, so it has to be assigned during the declaration not like a pointer which can be declared as an empty pointer then point to specific variable/object, point can be casting to a different data type but reference is fixed for that data type only, so a reference can be seen as an alias to the variable.

  • @anmol2757
    @anmol2757 4 года назад

    Man that's the best explanation I found online. Thanks a ton bro and kudos to your effort . All my doubts were cleared

  • @xYuki91x
    @xYuki91x 4 года назад

    You explained it waaaay better than my professor. I finally understood it thanks to your video!

  • @MukeshKumar-oc8or
    @MukeshKumar-oc8or Год назад

    Thank you for this tutorial! It was clear, concise, and easy to follow.

  • @4AneR
    @4AneR 4 года назад +3

    I like the idea of thinking about a reference as an always dereferenced pointer with constant value

  • @leam1978
    @leam1978 2 года назад

    before i switched my career to art, i was always confused about this. thanks for the explanation; might come in handy some day.

  • @gregholland11
    @gregholland11 2 года назад

    This was helpful. Always wondered what the difference was but never cared enough to Google it.

  • @Sub-zero1123
    @Sub-zero1123 4 года назад

    The best video that explains pointers. Thank you

  • @Gidid56
    @Gidid56 2 года назад +9

    The diagram gives the impression that ptr holds a meaningful value after int* ptr; It does not. It holds garbage. It does not get assigned any value. It will just contain whatever garbage is in memory the moment ptr gets created..
    Also references are under the hood pointers that behave like value types. But they are not value types. Once the original value object they are referring to goes out of scope, the refernce now is dangling (invalid). You have to make sure, that your original value object outlives the lifetime of the reference.

  • @dawidp4227
    @dawidp4227 2 года назад +30

    I'm just nitpicking here, but it's impossible to have two ints on addresses 0xA and 0xB, because int is usually 4 bytes, so the integer on address 0xA actually lives on 0xB, 0xC and 0xD too. I know it doesn't make a lotta difference, but I think it's good to know

    • @rocket2739
      @rocket2739 2 года назад +9

      A could be 0x66294701 and B could be 0x55399572
      In other words, A and B are names, and B != A + 1
      That's why he used uppercases instead of writing 0x0000000a and 0x0000000b

    • @francoisloriot2674
      @francoisloriot2674 9 месяцев назад

      it's also impossible to have 4 bits (single hex digit) memory address on any usable computer. So your knit picking missed the point that these just mean arbitrary addresses A and B.

  • @AhmedKhan-yw3wx
    @AhmedKhan-yw3wx 9 месяцев назад

    And here I was thinking pointers would be hard to tackle, thank you so much for such an easy explanation .

  • @robinlee-delisle8591
    @robinlee-delisle8591 7 лет назад +4

    Perfect explanation and the visualisation used really aided in my learning!

  • @tibyansuliman8657
    @tibyansuliman8657 5 лет назад

    Paul your videos saves me every time 😭❤️ thanks a lot ❤️❤️❤️❤️❤️❤️

  • @jasonjypark
    @jasonjypark 5 лет назад +1

    Your explanation was better than my professor's!

  • @fionaho4598
    @fionaho4598 3 года назад

    i appreciate your explanation, way better than my university professor!

  • @OpheliaSHolmes
    @OpheliaSHolmes 3 года назад

    I enjoy the way you explained pointers, the chart helped a lot. Thanks!

  • @sher.5027
    @sher.5027 3 года назад

    Thankyou. it was a great explanation compared to other youtube videos. Thanks again.

  • @ethannnnnnn
    @ethannnnnnn 6 лет назад +1

    Honestly the best explanation of pointers I have ever seen. The diagram helped an unbelievable amount. I can't thank you enough.

  • @Creuilcreuil
    @Creuilcreuil 7 лет назад +18

    basically a ref is an immutable pointer, i.e *int* * *const* ptr;
    which automatically deferenced by the compiler when used, then nulled

    • @ratgr
      @ratgr 4 года назад +6

      never nulled

    • @thulanitinashe6475
      @thulanitinashe6475 4 года назад

      can you explain more cause i am lost

    • @jaimealbertorocha5961
      @jaimealbertorocha5961 4 года назад +1

      Pointers have their own intrinsic address (memory address of the variable or object in question), while references do not. The intrinsic direction of the pointer is different from that of the variable or object it points to. Instead, the intrinsic direction of the reference is the same as the variable or object to which it was associated. The reference is simply an alias for the variable or object to which it is associated.
      As a complement, you can think of a reference as another name that is given to the variable or object to which said reference is associated. That is, the variable or object whose memory address is associated with the reference will no longer have a way of being called but 2. In other words, the variable or object that is assigned to the reference can be called with two different names, either with the name of the reference or with the name of the variable or object that is assigned to the reference.

  • @nikolayrangelov1081
    @nikolayrangelov1081 5 лет назад +63

    Hello, very good explanation! Can you cover in your next videos more advanced topics such as *&, **&. I know it is a combination of pointers and references, but extra explanation and exercises always help! Thank you!

  • @mykalesalad
    @mykalesalad 2 года назад

    Definitely less confusing now, thank you for the thorough explanation.

  • @yannmasoch
    @yannmasoch 6 лет назад +3

    Pointers and references in C++ are not easy to figure out, and your explanation makes things easier! Thanks :)

  • @muallaozdemir1012
    @muallaozdemir1012 2 года назад

    I loved how you explained this, so easy and clear. Thank you.

  • @punchline1729
    @punchline1729 Год назад

    His Tutorials are fantastic.
    I don't know why he didn't continue uploading tutorials

  • @baronvonmike
    @baronvonmike 2 года назад +1

    Finally, someone just explains what an "alias" is.

  • @corypheus1316
    @corypheus1316 6 месяцев назад

    bro , how simple is that Subject actually. Subscribed und liked. Thank u so much

  • @rajcodes100
    @rajcodes100 5 лет назад +5

    Great lecture but what I find a little tricky is that initially when we introduced the ref we used & ref = var , now if we want the pointer to point to var we write ptr = &var and if we want the pointer to point to ref which is var we write ptr = &ref .In a mathematical sense people can get confused here because initially & ref = var and (ptr = &var or ptr = &ref but &ref = var so in this sense it becomes like var = &var).

  • @jjoeygold
    @jjoeygold 2 года назад +1

    Integer pointers take two or more memory location however have the memory locations 0xA and 0xB one byte appart. memory size of the pointer is hardware specific and compiler specific and the memory locations should be 0xA and at minimum 0xC (2 bytes) or some 32bit compilers have integer sizes 4 bytes ie 0xA and then 0xE

    • @vasiliynkudryavtsev
      @vasiliynkudryavtsev 2 года назад

      Yep, I also spotted this anomaly. Unless his machine has int8_t as int or Harvard architecture.

  • @donyadabiri9906
    @donyadabiri9906 5 лет назад

    Great video. It completely cleared the difference between pointer and reference for me. Also, using diagram helped so much in understanding the concept.

  • @Kenforbes3
    @Kenforbes3 4 года назад

    Excellent explanation of the difference between a pointer and a reference.

  • @enigma2886
    @enigma2886 7 лет назад +11

    You are a life saviour ....man thank you so much....thank you so so so much !!!!!

  • @blackcoffeedevelopment3522
    @blackcoffeedevelopment3522 2 года назад

    short, simple, and helpful. Thanks!

  • @Maxpain666777
    @Maxpain666777 4 года назад +1

    Absolutely amazing on the splitscreen teaching. Thank you so much.

  • @lmthelex
    @lmthelex Год назад

    te amo loco, viva el conocimiento libre y a disposicion de todxs!!!!

  • @louisboscher33
    @louisboscher33 2 года назад

    Dude thank you so much, so useful, so well explained you are the best

  • @sarumironfort
    @sarumironfort 2 года назад +1

    The ptr has a location and address as well. You should point out that, and that by default the address to the vars would be sequential with offset of the previous ones size. Also as ptr points to zero it would *ptr actually show the value of whatever is at zero location. If these are statically defined then yes it would be preinit to zero but if it was on the stack it might not be zero.

  • @dastin7276
    @dastin7276 7 месяцев назад

    Excellent video. Excellent teacher. Thank You.

  • @HamzaBenfaddoul
    @HamzaBenfaddoul Год назад

    thanks, you are an amazing good explanation :) if you explain first how to assign the reference and the case that we can't do it with the reference and we can do it with a pointer it will be helpful

  • @DonBeleren
    @DonBeleren 5 лет назад

    Finally, someone explains this concept simply! :)

  • @ShubhrajyotiGhosh-y8e
    @ShubhrajyotiGhosh-y8e 15 дней назад

    Thank You very much for explaining so clearly.

  • @sebastienboutin8588
    @sebastienboutin8588 3 года назад +11

    Hey nice video. It could have been nice to explore in more detail the difference using references vs pointers as arguments with functions, inside classes, with more complex objects, etc... But thanks for the video anyway!

  • @jenweatherwax7113
    @jenweatherwax7113 5 лет назад +1

    This visual approach helped me a lot!!!

  • @crptc5707
    @crptc5707 4 года назад

    Much appreciated, it's clear and concise, saved us a lot and time and hassle!

  • @marziantulabot5512
    @marziantulabot5512 4 года назад +2

    In the last part about the reference. Does this mean that when we change the value of var, the value of ref also changes because it is pointing to the same address?

  • @SHADERSOP
    @SHADERSOP 2 года назад

    What a fantastic explanation - great work!

  • @CasanovaPugilist147
    @CasanovaPugilist147 3 года назад +1

    Quick question, I created variable int i = 3. Then I created int *p =&i . I printed the following and got the outputs p=0xfdc4, *p = 3, and &p=0xfdb8. I checked &i which equals 0xfdc4 which is what p equals since it is pointing to it. So &p is the memory address of the p pointer variable itself like how 0xfdc4 is the memory address of the i variable? To put it visually like in the video, the box of my p pointer variable would have 0xfdc4 inside the box and outside|underneath the box would be 0xfdb8 correct?

    • @hil449
      @hil449 2 года назад

      Exactly

  • @elias8294
    @elias8294 7 лет назад

    This was a great explanation. My C++ instructor skipped the chapter covering pointers, but our other chapters after that assume we understand them. She's as horrible as her rate my professor review said she was 😤

  • @reinaldoyang2546
    @reinaldoyang2546 2 года назад

    Very good explanation! easy to understand

  • @shivrajbhatti1074
    @shivrajbhatti1074 5 лет назад

    an example of the difference in functionality at the end would make this 💯🌊

  • @superpositif34
    @superpositif34 2 года назад +3

    Why *ptr has a good chance to be 0x0 without initialising it? In my opinion there is more chance *ptr is not 0x0 than 0x0.

  • @PunmasterSTP
    @PunmasterSTP 2 года назад

    This was incredibly useful. Thank you for sharing!

  • @tanmoydutta5846
    @tanmoydutta5846 2 года назад +1

    And that's why, pointers pose a security threat, whereas references don't.......

  • @hiTocopter
    @hiTocopter 2 года назад

    I commend people who want to learn this, because they're the ones who create managed languages which does all (or most) of this for us in the background.

  • @HelicopterRidesForCommunists
    @HelicopterRidesForCommunists 2 года назад

    Visuals helped tremendously. Thank you!

  • @brandicook8497
    @brandicook8497 4 года назад

    Thank you for simplifying this and for the visual representation. I actually understand it now !!!!

  • @osamaato921
    @osamaato921 8 месяцев назад

    it was a hell question in my mind after you answered it thank you

  • @abhishekshah11
    @abhishekshah11 4 года назад

    Clear and concise. Just the way I love it.

  • @najibkassab9254
    @najibkassab9254 5 лет назад

    Liked the idea of split screen.... helps visualising the code

  • @Decco6306
    @Decco6306 4 года назад

    im just now linking assembly language Ive been learning for the z80 for my calculator, and this connects so many connections that i haven't made. I totally get why pointers do what they do why and why they are usefull
    when writing to the address of an address port you are basically dereferencing a pointer just like in C.
    Crazy.

  • @ambientamben5059
    @ambientamben5059 5 лет назад +1

    if i change the value of a reference variable, would it also change the value of the original variable, or a variable where the reference variable is referencing to? for example if i change the value of ref to 21 would the value of var also change to 21?
    What would also happen if instead of placing the address of var, which is &var , to pointer ptr i place only var: ptr = var;
    would it show error? or vice versa *ptr = &var;

  • @jhondoe3381
    @jhondoe3381 3 года назад

    Thank you for explaining it so well, I finally understood it.