In this video I explain the difference between a C++ pointer and a C++ reference. Donate - bit.ly/17vCDFx STILL NEED MORE HELP? Connect one-on-one with a Programming Tutor. Click the link below: trk.justanswer... :)
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.
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.
@@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!
@@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....
@@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
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
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.
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
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
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.
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.
Definitely the best video on RU-vid explaining the difference between pointers and references. Also, thank you for not using all the programming jargon when explaining. Thank you!
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! :)
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.
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
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
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).
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!
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.
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.
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!
a reference is a pointer with more strict rules. it holds the address of other things in memory but it cannot be retargeted and must be initialized when created. this means you have less control but is safer since you cant accidentally point to bad memory locations. i usually use c so i am used to pointers but its just an option in c++
Not strictly true, you *can* accidentally bind your reference to a bad address by dereferencing an invalid pointer. It rarely happens, but does happen in practice with careless memory management and various mishmashes of semantics. I made a little test with g++ and this doesn't segfault till we try to read the reference which is effectively null: int* test_ptr = nullptr; int& test_ref = *test_ptr; printf("bound a nil reference "); printf("value of testref: %i ", test_ref); // segfault another way references are odd is that they apply value semantics to your pointer - so for example test_ref = some_other_variable; is assigning the variable that test_ref actually points to with the value of some_other_variable - and not making test_ref a reference to some_other_variable.and also C++ has operator overloading so if you have a class with an overloaded operator= then c++ will actually invoke that on your second usage of the equals operator with your reference variable. I actually prefer the explicitness pointers give nowadays because it hides less of whats actually happening.
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.
Why don't you initialize your int* ptr to 0 or nullptr instead of leaving it to maybe beeing null? Especially when teaching you should consider not leaving variables unitialized because you can easily overlook such a problem in larger projects..
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
You forget to mention that pointer have also his own address. By reference when you create name for variable, compiler is assigning address in memory, but for reference, name don't have address, is empty, then You can assign another name of variable just copying in that place address. it means that You have 2 names with this same address in memory. Where pointer is desighn to hold in memory address from another value. And have his own address. That's why You can point to pointer,and make pointer pointing to pointer which is pointing to another pointer.
it makes c++ highly efficient. If you call by value, basically the computer needs to look for the value in memory then access that memory then do something with it. But if you give it a pointer it misses the need to look for the memory.
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?
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?
Pointer variable and reference variable in c++ both stores address of the allocated data in memory. In other words, they both points or reference to a data. They only differ in usage. Reference variables are immutable, you cannot point it to another block of data in memory once assigned. When you try to access the value of a reference variable it implicitly dereferences to the value it is pointing to. Thats why they are called 'alias'. On the other hand, pointers can point to different allocations in memory even if you already assigned it. Also pointers can be null at the moment if the data you intend to point is allocated in the future. Also you need to explicitly dereference a pointer to access the value.
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.
So references are sort of like hard links (different name, same inode -> different name, same part of memory) and pointers are soft links (different name, different place in memory that contains the information on how to get to the data).