What is the Difference Between Pass By Value, Pass By Reference, and Pass By Pointer, C++

  Рет қаралды 118,682

Paul Programming

Paul Programming

7 жыл бұрын

In this video I explain the difference between pass by value, pass by reference, and pass by pointer in a C++ program.
Donate - bit.ly/17vCDFx
STILL NEED MORE HELP?
Connect one-on-one with a Programming Tutor. Click the link below:
trk.justanswer.com/aff_c?offe...
:)

Пікірлер: 112
@rajatmig29
@rajatmig29 5 жыл бұрын
paul, the way you explain and the calmness in your voice combine to give the viewer a very good experience. keep up the good job
@mytech6779
@mytech6779 2 жыл бұрын
Just for those passing by, the C++ committee recommendation is that raw pointers should no longer have a place in user code (as opposed to a few specific uses inside the STD library) std::unique_ptr is a full replacement for raw pointers with identical runtime performance while eliminating potential memory leaks.(unique_ptr also replaces auto_ptr)
@timi_t_codes
@timi_t_codes 11 ай бұрын
Thanks!!!
@andrewr.3478
@andrewr.3478 6 жыл бұрын
As a beginner I've been struggling with this concept for weeks now, but your video essentially​ clarified everything in my head. Thanks mate!!!
@sandlertossone1813
@sandlertossone1813 Жыл бұрын
Should make a series on C++. I've looked at a ton of video's on this and understand pointers. Your video's on these are the best of them all. After years of being confused or not being clear on certain small details on these subjects, you really cleared them up for me so a huge thank you. I hope you make a series on C++ explaining classes, inheritance, arrays, and other basics.
@vantran1189
@vantran1189 3 жыл бұрын
It’s so much easier to understand with your explanation & examples. Great thanks :)
@WonderCloudHD
@WonderCloudHD 6 жыл бұрын
I just wanted to say thank you for this great video. The examples you have provided were very helpful and very beneficial to my learning. I was really able to see the differences between the three methods, and really understand the concepts. Thank you.
@hunterkasa3158
@hunterkasa3158 3 жыл бұрын
Really done well, never had a single problem understanding this!
@Sof_net
@Sof_net 5 жыл бұрын
You are very good at explaining, clear with your choice of words and very calm. You could be a very good teacher.
@Shazbazz
@Shazbazz 3 жыл бұрын
I feel like I understand pointers better now, but I still don't understand why you would ever want to use them if you just just pass by reference instead.
@hannahm9259
@hannahm9259 3 жыл бұрын
Very nice, clean and comprehensive tutorial. Thanks!
@PaulProgramming
@PaulProgramming 3 жыл бұрын
Thanks!
@ezgieftekin4495
@ezgieftekin4495 6 жыл бұрын
This was so helpful. You explaind like it is so simple.I hope i don't get confused again.
@SerhatAtes
@SerhatAtes 4 жыл бұрын
but you will.. :)
@pepe6666
@pepe6666 5 жыл бұрын
thank you very much. remarkably clear. its like you made zero mistakes. remarkable actually
@yanezhekov5025
@yanezhekov5025 2 жыл бұрын
Giving examples is 50% of making sure someone understands it. The other 50% is testing stuff out yourself.
@scally9341
@scally9341 3 жыл бұрын
Still helping people in 2021 btw...
@zieglerai
@zieglerai 7 жыл бұрын
Great video!! Keep up the good work!
@solaaar3
@solaaar3 7 жыл бұрын
my mind has exploded.
@mryup6100
@mryup6100 4 жыл бұрын
Nice Try M9: 🤯
@SpellsOfTruth
@SpellsOfTruth 4 жыл бұрын
Is your mind gravy?
@prarabdh6295
@prarabdh6295 2 жыл бұрын
best channel ever
@ruannawe6157
@ruannawe6157 Жыл бұрын
Awesome content, thank you
@tylermccloudd6020
@tylermccloudd6020 3 жыл бұрын
Great video, thanks!
@mateuszsmendowski2677
@mateuszsmendowski2677 4 жыл бұрын
GREAT EXPLAINED :)
@Coorsil
@Coorsil 3 жыл бұрын
very well explained thank you
@OssaGhalyoun
@OssaGhalyoun 7 жыл бұрын
Mr. Programming what font are you using in that term and is that an xterm the font is nice.
@Nippius
@Nippius 7 жыл бұрын
Maybe I've missed something but i'm confused. What's the difference between using a reference and a pointer? They are both manipulating the same variable but when using a pointer you need the extra step of dereference it? Apart from that it's a good tutorial especially for people like who need to see things actually working :)
@PaulProgramming
@PaulProgramming 7 жыл бұрын
The easiest way to think about it is that a pointer can usually be instructed to point to different things over time, whereas a reference is referring to a specific thing.
@siniarskimar
@siniarskimar 6 жыл бұрын
To answer your question you need to know how computer gets data dynamically / from RAM. When creating a variable, VALUE is strored inside RAM with given cell address (RAM has cells, in which values are stored). NAME of variable is stored in different computer chip, let's call it "index chip" for now. This chip is like a map for a computer. When you use a normal variable, computer goes to this 'index chip' and gets it's name along with address in order to get the value. name ('index chip') ->address -> value This system is working fine, but can be slow as your program grows. This where pointers come in. Pointers store the addresses, as mentioned ealier, so computer doesn't need to search 'index chip'. Computer already knows the address, because of pointer, so it has direct way to get value. On top of that pointer can point/store any address. Meaning you can change where poiner is pointing at any time. They are also the way to make dynamic allocation work Ok, so pointer give us speed. What are references? References are like additional names to our address. THEY ARE NOT storing addresses! So when creating a reference, you are telling computer exactly what VARIABLE you want to have. In result, somewhat ignoring variable scope. Another difference is that, references are just names, so computer needs to do the same process of getting value as normal variable does. Summarizing: -Pointers are created for speed. -References are created for easier access.
@suhaimiannuar6008
@suhaimiannuar6008 5 жыл бұрын
Black DiamondPL thank you! really really help.
@mytech6779
@mytech6779 2 жыл бұрын
​@Name I thought i would have a short addition to the other comments but got carried away, anyway seams like a shame to delete it now. There are several layers of abstraction when including the operating system, but there generally is no "index chip". The operating system and CPU can see "real" memory addresses. "Real" as given by the memory controller, which is usually a chip on the motherboard that combines multiple physical modules and chips and converts basic linear address numbers used by the CPU to and from whatever is needed inside the actual memory chips. This is so the programmer does not need detailed information on exact hardware and so that the CPU does not need to be designed for exact memory hardware. The operating system will load an application into a chunk of memory and translates the real addresses of that chunk into virtual addresses. Another way to imagine it is that the compiled program uses relative addresses and the OS assigns the starting address. This way the compiled application is not hard coded to need a fixed set of real memory addresses. The CPU then starts reading binary instructions from the first memory address where the program was loaded. These instructions will include other memory addresses for the CPU to read either data or for a jump to another instruction(if not executing in order). So at the base level of the program it is all essentially pointers. THERE ARE NO OBJECT NAMES AT THE MACHINE LEVEL! (meant to be bold not yelling) At the machine code level there are only starting addresses and byte counts to fetch from those address and instructions for what to do to those fetched bytes. All the programming high level conceptual junk is wiped away. Now to understand the high level programming ideas of pass by value, ref, and pointer you need to understand the global-stack-heap allocation of memory that most programs use. The global part is where the base program was and is loaded into RAM, then small temporary chunks of RAM [frames] are stacked on this for each function call, this is the "stack". Pass by value is a copy operation and the required data from the global space is copied to the stack frame for use by the function, again kind of like the situation with the main application and OS the function typically only knows relative addresses within its frame. The function at compile time would not normally know addresses in the global area nor the relative distance to global. When the function operation is complete its frame is destroyed "popped of the stack". When a function calls a function you get more frames stacked up and this is why a function can't know its relative position to global variables at compile time because it won't know its stack height or or the global area size. Some high level programming languages copy values by default and others pass by reference by default, it is only a design choice to fit a programming style. No hardware or strict logic constraints require one or the other to be the default. "Reference" will use the existing address of an object [data] rather than creating a copy at a new address that is within the current stack frame. At a final machine code level there is no difference between a ref and a pointer but there is some difference at the compiler [optimizer] level and for ease of programming. The referenced object address can be in global, stack, or heap. So both value and ref are created as pointers within the binary machine code, but they are specific restricted use cases so the compiler can better optimize and the programmer gets less bugs debug. A "pointer" can be assigned any address and can be used with math [just like an int math] to alter the pointed at address while the program is running. The array syntax "z[0]" is syntax sugar, it is really just pointer math. "= z[3]" is the same as "= *ptr + 3" the pointer form gets complex with multi-dimensional arrays. Pointers are commonly used with heap memory, although they can be used with stack and global there is not much need. Heap is not orderly like the stack of frames, but heap is able to store much larger data structures and keep them for arbitrary lengths of time as heap memory is only released manually; either explicitly within the program(best), by a garbage collector function (easy but not suitable for some programs due to unpredictable lag, and may not catch 100% of leaks), or heap is always released when the program terminates and all of its memory is recovered by the OS (bad choice, only suitable for the most simple and well considered programs, otherwise this is an almost certain memory leak). Objects stored on the heap are sort of a cross between stack and global, like stack they are not part of the base machine code and so are safer to manipulate without changing important starting values, and like global objects heap objects are not tied to the life of a function call or the fixed size of a stack frame. So the real underlying question is why waste time copying a value?(I mean where you are not required by logic to save the original value) Its a safer style and easier to debug, and the way it copies is basically at no performance cost, the variable is read from the original address into the CPU register, used for whatever the function needs, then the result is written to the new address instead of overwriting the original address. In other words when properly compiled and optimized there is no separate copy step it is just dumping the output in location B instead of A.
@nailsonlandim
@nailsonlandim 4 жыл бұрын
Thanks a lot!
@mrpor9541
@mrpor9541 5 жыл бұрын
Finally i got it!!!!
@divyasoneji2639
@divyasoneji2639 4 жыл бұрын
Thank you!!!
@VeritasEtAequitas
@VeritasEtAequitas 2 жыл бұрын
So a reference functions as if it's a sort of "static" pointer, referring only to the named variable and cannot be changed to point to a different one.
@private9062
@private9062 2 жыл бұрын
Sorry for asking this rookie question, but I thought that in C++ you would normally use: cin/cout , instead of printf/scanf and all the placeholders. Can I use both? Video is amazing btw!
@dragonslayer2337
@dragonslayer2337 2 жыл бұрын
You might of figured it out but printf and scanf I believe are from C. Since C++ is a superset of C it makes most C code valid in C++. So cin and cout is the C++ way to input and output information and printf and scanf is the C way to input and output information.
@DJHyunKim
@DJHyunKim 4 жыл бұрын
i simply love you
@RSP13
@RSP13 Жыл бұрын
great!
@mattiacervo8258
@mattiacervo8258 6 жыл бұрын
Eccezionale!
@ThanhTrantrancongthanh
@ThanhTrantrancongthanh 7 жыл бұрын
can you explain about different way of return, like return by value, ...
@michrisoft
@michrisoft 7 жыл бұрын
return by value would just be making the function an int/double/float/etc. instead of a void and having a return val; at the end.
@industrialdonut7681
@industrialdonut7681 3 жыл бұрын
I'm a little confused only on why doing *ptr = 30; works like it does. I would've thought that doing *ptr anywhere is an 'r value' and thus can't assign something to it
@chuckwieser7622
@chuckwieser7622 3 жыл бұрын
I am confused too Paul Programming... Why does "ptr" = "xptr", making them both 30? thank you for your video in any help clearing up this question we.
@varun_n1729
@varun_n1729 7 жыл бұрын
+Paul Programming Which IDE are you using?
@bla7091
@bla7091 6 жыл бұрын
It looks like Sublime Text to me
@Farligefinn
@Farligefinn 6 жыл бұрын
i second that
@kal5211
@kal5211 3 жыл бұрын
My man.
@amolgaikwad4114
@amolgaikwad4114 4 жыл бұрын
I would like to to know, pass_by_reference and pass_by_pointer gives same result, so when to use pass_by_reference and when to use pass_by_pointer ?
@atlantic_love
@atlantic_love 2 жыл бұрын
Same. He failed to explain the why or use cases. Practically a useless video.
@haroldmcbroom7807
@haroldmcbroom7807 2 жыл бұрын
Thanks for the video, by the way, helped me understand this stuff. Question... In the video: int* xptr = &myVal; //...why not just use passByPtr(&myVal) ?
@n6rt9s
@n6rt9s Жыл бұрын
to demonstrate how pointers work without causing any further confusion
@laureven
@laureven 2 жыл бұрын
Thank You, Cool video, but most important element is not explained. Why reference is added to c++ if pointer is able to do the same thing. So, reference is redundant so far, but it has to be a reason it was added to c++, and if You have a title "What is the difference..." I would expect that the reason is more important than execution mechanics :) ...if anybody knows a video where the reason is explained, I will be supper grateful :)
@tajrianislam4993
@tajrianislam4993 5 жыл бұрын
why use printf over cout?
@vertigo6982
@vertigo6982 5 жыл бұрын
@@arthur_camara he should change the title to C mixed in with C++. It's misleading to teach C and say it's C++. It's bad practice imo. ESPECIALLY in a Pointers video! Might as well call this video C with Pointers.
@winhtut1187
@winhtut1187 5 жыл бұрын
all the man are kidding? almost features of c can use in c++... i like printf
@cabreram.4734
@cabreram.4734 4 жыл бұрын
@@arthur_camara how annoying. Not everyone knows C to assume this awfulness.👎🏿
@johnsknows3135
@johnsknows3135 Жыл бұрын
If you pass in the ref you are using the actual value. If you pass in the value you are passing in a copy. Thank you for telling me a straight answer ! besides the value been the copy and the ref the real thing being a stupid way of doing it, people in the community make it far worse by being cryptic about it.
@nielsdaemen
@nielsdaemen 5 жыл бұрын
Why not use an IDE?
@solaaar3
@solaaar3 7 жыл бұрын
which IDE are you using?
@aimalazmi4712
@aimalazmi4712 7 жыл бұрын
Sublime Text
@eldarismailov655
@eldarismailov655 7 жыл бұрын
Which editor do you use?
@eldarismailov655
@eldarismailov655 7 жыл бұрын
OK, I found here(comments). sublime-text
@abaja1931
@abaja1931 3 жыл бұрын
10/10
@jameswright4948
@jameswright4948 3 жыл бұрын
what ide does he use?
@mytech6779
@mytech6779 2 жыл бұрын
Looks like GNU-linux just a text editor and the Bash command line. Though he could have combined 'clear ; compile && execute' into one line that can be recalled with the up arrow. I Even mapped the equivalent of save and all that that to the F5 key in my text editor, "F5" BAM! save compile execute.
@SerhatAtes
@SerhatAtes 4 жыл бұрын
i saw in comments that people confused about c syntax; c++ is superset of c that means any c code can be build and run with c++ compiler
@checho_tala
@checho_tala 3 жыл бұрын
You're certainly right with that fact. However the people are right about the use of the syntax, it's clearly c++ so you should use the idiomatic syntax of c++, which involves the use of std::cout in the standard library and avoid using the C libraries and functions.
@mytech6779
@mytech6779 2 жыл бұрын
@@checho_tala Mostly, but I believe printf() syntax is superior to cout for many uses, printf() is even superior to python print(). [ And have you ever tested the effect on compile optimization, huge improvement with printf() vs cout, though this is not a concern unless there is a lot to print. Also " "; is usually better than ::endl; though endl will always flush the buffer may not be flushed immediately.]
@SpellsOfTruth
@SpellsOfTruth 4 жыл бұрын
Is this correct? -use pointers and pointer refs when datatype is larger than primitive datatype -diff between pointer and reference is that a pointer can point to more than 1 addr while a ref points only to 1 addr. -diff between func(I64 ptr), func(I64 &ptr), func(I64 *ptr), func(I64 * &ptr): -pass by value means copy param and param will not change at the end of function -pass by ref means no copy param and param will change at the end of function -pass by pointer means copy param and param will not change at the end of function -pass by pointer ref means no copy and param will change at the end of function -line carot '->' does not mean 'points to', it simply means ptr 'accesors' just like the dot '.' key means 'accessor'.
@RDD87z
@RDD87z Жыл бұрын
i didnt really understand the difference betwen pass by reference and pointer, one takes the real variable, and the other takes the value of the variable. but... in which scenarios one is better than the other.. i think i would need some more examples to really understand the difference. Thank you anyways.
@minhazulislam4682
@minhazulislam4682 Жыл бұрын
him: ***writes in cpp*** also him: Imma use the motherf*ing format specifiers here too.... I know the above joke is silly, but I had to do it. Anyway, great content. Keep'em coming.
@Metastate12
@Metastate12 4 жыл бұрын
Use cout in C++ tutorials.
@mytech6779
@mytech6779 2 жыл бұрын
I actually preffer the printf syntax in many cases. It's like a more capable python print()
@TR_Arial
@TR_Arial 2 жыл бұрын
Tbh sometimes using printf is better, at least for me, for example if I'm gonna be needing a lot of place holders I don't wanna spam "
@swarnasekhardas8576
@swarnasekhardas8576 5 жыл бұрын
The code which you wrote of pass by reference is not working.There is error is this: void passByRef(int & ref); Later i found the error. Actually c does not support pass by reference, c++ supports. If you write this in c++ it will work fine.
@mytech6779
@mytech6779 2 жыл бұрын
For the writing portion C is a part of C++. I Think you mean if you use a C++ compiler it will work but not with a C compiler.
@TheAwesomeDudeGuy
@TheAwesomeDudeGuy 7 жыл бұрын
I found it weird that you could make a 14 minute video on this subject without mentioning the word "address". Also, it wasn't clear what exactly each operator (& and *) does.
@GenerationzYT
@GenerationzYT 7 жыл бұрын
10:05.
@TheAwesomeDudeGuy
@TheAwesomeDudeGuy 7 жыл бұрын
Hah, totally my bad.
@PaulProgramming
@PaulProgramming 7 жыл бұрын
Thanks for the feedback. I have a video in the works that I am expecting to publish next weekend that will discuss & and * more.
@GenerationzYT
@GenerationzYT 7 жыл бұрын
Paul Programming It's actually really convenient you posted this video, as I just had a fellow class mate ask me about all three of those examples. So I linked him the video yesterday. Thanks for making my job easier xP
@TheAwesomeDudeGuy
@TheAwesomeDudeGuy 7 жыл бұрын
Sounds great. Looking forward to it!
@postmaster2211
@postmaster2211 4 жыл бұрын
it’s 2016. why would you use C based libs and C based prinf?
@SerhatAtes
@SerhatAtes 4 жыл бұрын
c++ is superset of c that means any c code can be build and run with c++ compiler
@mytech6779
@mytech6779 2 жыл бұрын
@@SerhatAtes There is one keyword in C that has no equivalent in C++. I don't know why, maybe just to make people ask.
@Emester123
@Emester123 6 жыл бұрын
you should print it step by step not all in one go, as a novice my mind is freaking out ahaha
@blue_name_warrior
@blue_name_warrior 2 жыл бұрын
It would be perfect to add "ptr += 10" or something to manipulate inside passByPtr function, and print 'ptr' itself before & after in main. Spoiler alert: It would not change.
@atlantic_love
@atlantic_love 2 жыл бұрын
You explain what it does, but you did not give any use cases for passing by copy or pointer. So I still don't understand why we really would do each of these.
@ror996
@ror996 Жыл бұрын
In conclusion reference and pointer works the same. So use reference all the time because pointer is kind of confusing...
@AnimeGIFfy
@AnimeGIFfy 2 жыл бұрын
i feel like this video didn't really explain the difference between ref and ptr.
@umarajmal6216
@umarajmal6216 4 жыл бұрын
Anyone else learning c++ as a beginner it would be great to talk with another person...
@sammiekarani371
@sammiekarani371 4 жыл бұрын
Yeah, here, +254758403330
@umarajmal6216
@umarajmal6216 4 жыл бұрын
@@sammiekarani371 from which country u r ?
@umarajmal6216
@umarajmal6216 4 жыл бұрын
is this ur whatsapp number
@nielsSavantKing
@nielsSavantKing 2 жыл бұрын
Sorry, but wh you are using printf and not cout?? printf is more in C. Cout you are using in C++
@mytech6779
@mytech6779 2 жыл бұрын
printf() is superior in several ways, cout is not great.
@AnimeGIFfy
@AnimeGIFfy 2 жыл бұрын
i guess there are centrists in the dark/light mode community too
@bombdotcomist
@bombdotcomist 3 жыл бұрын
I'm sorry but 12:36 line 13 makes no sense. The output should print out the ADDRESS of the xptr, NOT the value. Suggest you make a proper video that better explains this
@ktan18879
@ktan18879 6 жыл бұрын
Clearly it's c, c++ use cout and not printf
@Farligefinn
@Farligefinn 6 жыл бұрын
Clearly it's not c, since it's illegal to pass by reference in c!
@ShadowBurn680
@ShadowBurn680 6 жыл бұрын
Its C++ but hes using syntax from C which from what I've been told while yes it works is bad practice
@SerhatAtes
@SerhatAtes 4 жыл бұрын
c++ is superset of c that means any c code can be build and run with c++ compiler
@supertonyxd
@supertonyxd 5 жыл бұрын
I think it is a c, but not c++
@user-vn4yl3fr9f
@user-vn4yl3fr9f 5 жыл бұрын
No.
@kopuz.co.uk.
@kopuz.co.uk. 5 жыл бұрын
Yeah you're right.. so many people must think that they're writing correct c++ but in reality its mostly c with a hint of c++.
@SerhatAtes
@SerhatAtes 4 жыл бұрын
c++ is superset of c that means any c code can be build and run with c++ compiler
@Reivivus
@Reivivus 6 жыл бұрын
Yeah, I think I'm just going to stick to passing by references! I'm gonna stay away from pointers!!
@harkirehal258
@harkirehal258 Жыл бұрын
They should fire college professors and use this video instead.
What is the Difference Between a Pointer and a Reference C++
7:58
Paul Programming
Рет қаралды 421 М.
Introduction to a Double Pointer C++ (Pointer to a Pointer)
9:16
Paul Programming
Рет қаралды 36 М.
🍟Best French Fries Homemade #cooking #shorts
00:42
BANKII
Рет қаралды 56 МЛН
IS THIS REAL FOOD OR NOT?🤔 PIKACHU AND SONIC CONFUSE THE CAT! 😺🍫
00:41
Essentials: Pointer Power! - Computerphile
20:00
Computerphile
Рет қаралды 461 М.
Should I pass by const reference or by value?
10:45
The Cherno
Рет қаралды 98 М.
Hollow Knight Has Been Recreated in Minecraft
17:27
fireb0rn
Рет қаралды 53 М.
Function Pointers in C++
12:41
The Cherno
Рет қаралды 380 М.
Pointers and dynamic memory - stack vs heap
17:26
mycodeschool
Рет қаралды 1,4 МЛН
What does int argc, char* argv[] mean?
10:11
Paul Programming
Рет қаралды 349 М.
C++ Examples - Pass by Value vs Reference vs Pointer
11:53
Caleb Curry
Рет қаралды 21 М.
Master Pointers in C:  10X Your C Coding!
14:12
Dave's Garage
Рет қаралды 279 М.
How to Create a Linked List C++ Introduction to Linked Lists
12:24
Paul Programming
Рет қаралды 920 М.