@@Quaggabagel exactly what i was thinking as well, regardless im sure he gets a lot more support not asking and seeing what happens.. patreon is there for a reason..
The speed you go is perfect, most tutorials are too slow. I lose interest and get nothing. This isn't overly fast and can be followed, also you can tell you really know your stuff so if just flows. Good work, thanks.
You can play this at x0.75 or at x1.25 up to your personal preference. I am a bit ashamed to say but I might need x0.5 to get some understanding of the matter :)
Thank you so much. I've heard of this copy constructor topic many times and never understood it. You're the first person to explain WHY it's useful and the problem it solves.
Even though I've already been through most of this stuff, I love watching your videos 'cause they're such a great way to remind me of some details I've forgotten, provide another viewpoint on some of these topics and deepen/solidify my understanding of them. If it weren't for these videos I'd probably have a whole lot of "backtracking" to do at certain points but just watching one of your videos every day or two really helps rearrange all this stuff in my head in some kind of orderly manner ^^ Keep up the good work man, this series is basically the best online resource ever to do that sort of thing
Pretty much the same for me. Another benefit is, that I learn better ways to explain stuff, sometimes new team members will not be very good at C++, so I can use some of the examples in these videos when they have problems.
So true. I thought I have understood all about copy constructor until I sit down and watch this video again and then I go "Ahhhhh so that is how it works"
the best video for deep and shallow copy you really got concept clarity in each video really appreciate your work for society! love your work and explaining
As someone who learned C and Java at Uni, and is trying to learn C++, this was something that I didn't realize was important until recently. I think this helped solidify a few things in my head. I assume you're going to talk about Move constructors soon too.
How can I be so information-attended and creative in writing code and remembering it without facing any obstacles? I mean u're so fast, so good, keep going brother.
Personal Notes: -Shallow copy becomes a problem for heap-created objects, not for stack allocated objects(might needs check) -Deep copy is performed by adding copy constructor. After writing copy constructor, you can use “entity1 = entity2” for deep copying -Explained pass by value vs pass by reference. It is safe to use const reference for the function not to be able to modify the object.
If you cannot assume `string` is null-terminated, then `m_Size` will be wrong, because `strlen()` counts characters until it finds the null character `'\0`. So you could update the constructor to accept the length as a parameter, or just be consistent in your assumptions.
The most perfect and not unliked video series on youtube. U rule my Career propably, at least you have a signifant influence about my clarity. I have to thank u
Ever since I stumbled across your channel , it has become a routine to watch one or more of your videos . I don't know it's like an addiction . You have such a clarity in your understanding at such an early age . Awesome and good luck.
This literally gave me the solution to an issue I was having related to dynamically creating pointers inside of a base class. I narrowed down the issue that the same location in memory was being deleted twice, but I didn't know the next step. Then this video got reccomend almost as if youtube just knew lol. I'll have to implement the copy constructor and try it out.
you said at 1:24 "so what I'm trying to tell you is always pass your objects by const reference" and I misunderstood that, trying to pass pointers to arrays by reference... it was a 1-hour nightmare fixing the resulting bugs
Ah, looks like I have reached my first soft cap. Everything up to here was pretty easy to understand for me but I'm starting to feel that I have not understood the preceding topics well enough to follow this 100%. I get the problem you are trying to demonstrate but the stuff around it is a bit too shaky still. I will have to rewatch some of the previous videos and practice some more and I'm sure I'll understand this better because your explanation is done very well :)
This is very arguable. References are just dereferenced pointers and there's not a lot of difference between them. In fact, pointers have a lot more power than references because they can be null, changed and mutated. References never can.
You talk really fast and put so much information in just 5 seconds. For a beginner I find Your channel intimidating to watch as i really just understand the first minute and everything comes after slips away
There is no need to separately copy the NULL terminator in the constructor, you could've just used the m_Size + 1 in the memcpy, just like in the copy constructor, since if the string wasn't properly terminated, the strlen wouldn't work properly as well.
Thank you so much Yan for these amazing videos. I don't have the money to support you on Patreon but one day I will definitely do it. Love from India :)
The only exception that I can think of at the moment to the pass by const ref advice is with primitive types that can be created on the stack.(x86 specific) And that is because the speed of creating, using, and deleting stack frames is pretty close to the minimum lag physically possible due to a combination of cache coherence, registers, and the way the stack pointer works. In some cases the optimizer will not even assign a memory location to a stack primitive, it may live entirely within a cpu register; and deleting a frame is only a matter of decrementing the stackpointer which is generally a one CPU-cycle operation. Still its a pretty narrow case where a program would spend a substantial amount of time creating and deleting primitives. Along with the usual advice to not optimize too much until after getting the logic correct and profiling to find that big O chunk of code. (A bit of consideration for runtime efficiency is warranted during the initial draft just to avoid huge structural changes later on, just don't spend a bunch of time on it.)
@The Cherno. Pls, pls, pls make a Cherno branded T-shirt. I wanna but its to support you cuz I love what you do and I want others to know about you. the best way for me to spread the good word about your channel is with a T-shirt!
Charno... Oh damn... and then I heard in my mind... "I am Charno, god of strive, god of slaughter, god of death! When there is pain, I am there. When there is suffering, I flourish. When there is a joy... well, one could hardly have joy, without another suffering, no?.. " Great series, by the way :)
For some reason, at my old place of work work our style guide was against passing by reference but to use pointers instead. I'm not sure if they determined it was actually faster, or because they preferred more "C" style code. I don't think the advice was much heeded, though.
To those who don't know what the keyword "friend" does: Friend is a keyword that allows functions declared outside of the class to modify private variables inside a class.
At 8:01, since you were using strlen which calculates using null terminator, there will be a null terminator for that string, so it is safe to just copy it.
Not for me, I got some garbage values after using memcpy() to copy the string and print it out. However writing this fixed my issue: m_buffer[m_size] = '\0';
Hi, I have a question where I could not find an answer yet: I want to have a stack allocated array initialized by a copy constructor. With the std::array it looks like following. class Polynomial { std::array my_array; int size; public: Polynomial(const Polynomial& p) : my_array{ p.my_array }, size(p.size) {} } How can I implement this without the std::array but only a normal int my_array[5]; Thanks :)
8:06 That's safety trick isn't gonna work, because strlen gives you len based on when he meets null, e.g if we gives him char a[] = {'a'}, then it's len may be not 1, but 32, or 40, or whatever any number, maybe even cause some errors.
I just tried this technique and it work for object on the heap too.. so now I realized const reference is used when the object we want to use does not need to be changed.. although it is const it's value can be assigned to another variable like std:: vector or array
At 8:02 that would make no difference, because without terminating null we have no way of knowing the string length. strlen() actually keeps counting bytes until (char)0.
How can I distinguish if the constructor in the instance you write is a copy constructor rather than a constructor with parameters? I feel a bit confused.
A copy constructor explicitly pulls values from an existing class object (i.e. other) to create a copy it. A typical constructor simply creates a new object instance of a class.
@12:50 ok so when i write String name="anybody"; String anotherName=name; this means a shallow copy only i.e only copy the pointer to the object but not the object itself so basically when i write String name; is this actually a pointer to a "String" object? on the stack?
now realizes that copy constructor is useful when you want to copy object on the heap i.e when you call "new " keyword if its on the stack there is no problem but the problem is on the heap which is when one of the objects involved in the copying process dies, another object will get reference to an object that already being deallocated..so you must provide your own deep copy using memcpy() function to copy the objects/value to another memory address so when one object get deallocated another object being copied still lives
Cherno you've said that if you can't be sure the string is null terminated, then just plop in a zero at the end of the string. But IIRC strlen() makes that assumption for you so the deliberately plopping in a zero at the end by you is irrelevant really, 7:55
finally a series on youtube I don't have to put on 2x speed lol
Agree. Watching on 1.5x speed. Can't go higher.
I am really curious If this is filmed at that speed. It is insanely fast
Up until episode 30 or so I was watching at 2x speed just so i can get back to the opengl series
I'm at 50% speed and finally I understand he speaks english...
Still watching at 2x speed. Otherwise he would be too slow
We're so lucky this C++ series are free x)
Until he realises he can buy a t-rex with his course money if it wasnt free.
then again asking 10$ for this course wouldn't be all that much
Laurentiu Stefan it is for some people who just want to learn
absolutely
@@Quaggabagel exactly what i was thinking as well, regardless im sure he gets a lot more support not asking and seeing what happens.. patreon is there for a reason..
The speed you go is perfect, most tutorials are too slow. I lose interest and get nothing. This isn't overly fast and can be followed, also you can tell you really know your stuff so if just flows. Good work, thanks.
I am worried, he's too fast
You can play this at x0.75 or at x1.25 up to your personal preference. I am a bit ashamed to say but I might need x0.5 to get some understanding of the matter :)
@@marindraganov8765 If I don't understand something, I keep repeating it
@@this_is_mac While loop?
@@pierfrancescopeperoni
while(understanding == false){
ReplayVideo();
}
Every single video in this series is so incredibly informative and intuitive and the fact that it's a hundred episodes long makes it even better
7:25 thank you for the solution for fixing random garbage at the end of a dynamic char array.
I came here looking for copper
But found gold
Thank you so much. I've heard of this copy constructor topic many times and never understood it. You're the first person to explain WHY it's useful and the problem it solves.
I've been rewatching this series just for fun, and as always the videos are excellent, informative, and concise.
Thanks!
Even though I've already been through most of this stuff, I love watching your videos 'cause they're such a great way to remind me of some details I've forgotten, provide another viewpoint on some of these topics and deepen/solidify my understanding of them.
If it weren't for these videos I'd probably have a whole lot of "backtracking" to do at certain points but just watching one of your videos every day or two really helps rearrange all this stuff in my head in some kind of orderly manner ^^
Keep up the good work man, this series is basically the best online resource ever to do that sort of thing
Pretty much the same for me. Another benefit is, that I learn better ways to explain stuff, sometimes new team members will not be very good at C++, so I can use some of the examples in these videos when they have problems.
So true. I thought I have understood all about copy constructor until I sit down and watch this video again and then I go "Ahhhhh so that is how it works"
the best video for deep and shallow copy
you really got concept clarity in each video
really appreciate your work for society!
love your work and explaining
As someone who learned C and Java at Uni, and is trying to learn C++, this was something that I didn't realize was important until recently. I think this helped solidify a few things in my head.
I assume you're going to talk about Move constructors soon too.
Yes, we'll get into move semantics eventually. :)
17:48 Little did he know it would take him 3 More Years...
lol! me too, I actually watched the l, r values first
lol
ive said this before, and ill say it again.. this is one of the most informative code channels on youtube.
Man, this series is good. Fast, to the point and makes me feel like I've just sniffed 20 grams of speed.
How can I be so information-attended and creative in writing code and remembering it without facing any obstacles? I mean u're so fast, so good, keep going brother.
this cleared concept of shallow vs deep copy, copy constructor, along with operator overloading & importance of pass by reference, brilliant!
This is one of the greatest content I have seen on C++ copy constructors...Thanks Cherno
Personal Notes:
-Shallow copy becomes a problem for heap-created objects, not for stack allocated objects(might needs check)
-Deep copy is performed by adding copy constructor. After writing copy constructor, you can use “entity1 = entity2” for deep copying
-Explained pass by value vs pass by reference. It is safe to use const reference for the function not to be able to modify the object.
If you cannot assume `string` is null-terminated, then `m_Size` will be wrong, because `strlen()` counts characters until it finds the null character `'\0`. So you could update the constructor to accept the length as a parameter, or just be consistent in your assumptions.
The most perfect and not unliked video series on youtube. U rule my Career propably, at least you have a signifant influence about my clarity. I have to thank u
no kidding, i havent seen many but these are high quality c++ videos
detail is rich, pace is balanced, a sub is gained
I recently found these C++ videos on YT. They're excellent. Thanks for the effort Cherno.
Just want to say thanks for preparing me for my job interview.
I am new to C++ and your tutorial just save my life, thanks a lot!
Ever since I stumbled across your channel , it has become a routine to watch one or more of your videos . I don't know it's like an addiction . You have such a clarity in your understanding at such an early age . Awesome and good luck.
This literally gave me the solution to an issue I was having related to dynamically creating pointers inside of a base class. I narrowed down the issue that the same location in memory was being deleted twice, but I didn't know the next step. Then this video got reccomend almost as if youtube just knew lol. I'll have to implement the copy constructor and try it out.
you said at 1:24 "so what I'm trying to tell you is always pass your objects by const reference" and I misunderstood that, trying to pass pointers to arrays by reference... it was a 1-hour nightmare fixing the resulting bugs
Ah, looks like I have reached my first soft cap. Everything up to here was pretty easy to understand for me but I'm starting to feel that I have not understood the preceding topics well enough to follow this 100%. I get the problem you are trying to demonstrate but the stuff around it is a bit too shaky still. I will have to rewatch some of the previous videos and practice some more and I'm sure I'll understand this better because your explanation is done very well :)
Thank you so much for helping with that piece of code for 14:32
Thank you. I knew vaguely about copying, but thanks to you I understand it clearly now. I'm also watching other videos from the C ++ series.
probably the best cpp video it covers so many things haha
I love the humor this man has.
C++ is a great language.
I admire sir. Bijarn Stroustrup as well as sir. Dennis Ritchie.
Creation of "Reference(&)" is one of the good improvement of C++ comparing with C.
Reference gives more "memory efficiency" to us.
Also if the function accept reference you don't have to check if the argument is null or not
This is very arguable. References are just dereferenced pointers and there's not a lot of difference between them. In fact, pointers have a lot more power than references because they can be null, changed and mutated. References never can.
this is the most interesting episode in the series :)
Congrats on 500K subs man !
Charno - No char for you
You talk really fast and put so much information in just 5 seconds. For a beginner I find Your channel intimidating to watch as i really just understand the first minute and everything comes after slips away
same exact problem here
i dont know what to do
thanks alot man, you are the best. for me this is heavy stuff alr, but you make me so easy to understand.
You are talking so fast. but your style is very clear. Thanks for sharing.
TheCherno has taught me well; I saw the copies coming with the PrintString() function as he always passes by const ref to avoid this exact thing
C++ is so much more exciting than Python to learn...
Deep Object.. Shallow Copy.. I saw that look! So many great analogies to make lol
best video explaining copy and deepcopy
Thanks for this video! It is amazing.
Greetings from Germany!
Awesome BUT so fasssst! I have to watch the video many times to better understand. Anyways you are still my professor
You sir are a very good, thanks for these series!
Thanks for making a good example. It cleared Copy constructor, Deep/Shallow copy and reference.
There is no need to separately copy the NULL terminator in the constructor, you could've just used the m_Size + 1 in the memcpy, just like in the copy constructor, since if the string wasn't properly terminated, the strlen wouldn't work properly as well.
yes that worked for me to instead of his way, thanks :)
Agreed
Kinda glad he did it wrong though, the extra steps helped me understand it better and reading the comments gives one expertise.
Yeah I got confused about this exact thing.
Thank You. This was an awesome video on c++ concepts.
this video is still helpful in 2022. Thanks a bunch
I love you Charno
Very helpful. Also note that you will make a copy when you return a String object
Thank you so much Yan for these amazing videos. I don't have the money to support you on Patreon but one day I will definitely do it. Love from India :)
The only exception that I can think of at the moment to the pass by const ref advice is with primitive types that can be created on the stack.(x86 specific) And that is because the speed of creating, using, and deleting stack frames is pretty close to the minimum lag physically possible due to a combination of cache coherence, registers, and the way the stack pointer works. In some cases the optimizer will not even assign a memory location to a stack primitive, it may live entirely within a cpu register; and deleting a frame is only a matter of decrementing the stackpointer which is generally a one CPU-cycle operation. Still its a pretty narrow case where a program would spend a substantial amount of time creating and deleting primitives.
Along with the usual advice to not optimize too much until after getting the logic correct and profiling to find that big O chunk of code. (A bit of consideration for runtime efficiency is warranted during the initial draft just to avoid huge structural changes later on, just don't spend a bunch of time on it.)
8:00 How would strlen() find out the lenght without a '\0' ?
@The Cherno. Pls, pls, pls make a Cherno branded T-shirt. I wanna but its to support you cuz I love what you do and I want others to know about you. the best way for me to spread the good word about your channel is with a T-shirt!
0:01 - Yes! The subtitle was near perfect! Just misspelled his name tho. Great job UA-cam :p
Excellent example, really clear and concise, well done.
Charno...
Oh damn... and then I heard in my mind...
"I am Charno, god of strive, god of slaughter, god of death! When there is pain, I am there. When there is suffering, I flourish. When there is a joy... well, one could hardly have joy, without another suffering, no?.. "
Great series, by the way :)
For some reason, at my old place of work work our style guide was against passing by reference but to use pointers instead. I'm not sure if they determined it was actually faster, or because they preferred more "C" style code. I don't think the advice was much heeded, though.
To those who don't know what the keyword "friend" does:
Friend is a keyword that allows functions declared outside of the class to modify private variables inside a class.
but also of classes
Shin Lim does a good job teaching C++.
Hello where i can find more information about new Vector() in 2:14 when you heap allocate it. What it actually does?
Such a fantastic lesson! Second time to review this.
This was a really comprehensive tutorial. Thank you!!
At 8:01, since you were using strlen which calculates using null terminator, there will be a null terminator for that string, so it is safe to just copy it.
Not for me, I got some garbage values after using memcpy() to copy the string and print it out.
However writing this fixed my issue:
m_buffer[m_size] = '\0';
Great job with this series!!
Nice one :) i get the ideas of what that actualy does far better Then in highscool explanation
Hi, I have a question where I could not find an answer yet:
I want to have a stack allocated array initialized by a copy constructor. With the std::array it looks like following.
class Polynomial
{
std::array my_array;
int size;
public:
Polynomial(const Polynomial& p)
: my_array{ p.my_array }, size(p.size) {}
}
How can I implement this without the std::array but only a normal int my_array[5];
Thanks :)
Great summary, excellent, simple examples
Aren't you already assuming the string is 0 terminated when you measure its length using strlen?
8:06
That's safety trick isn't gonna work, because strlen gives you len based on when he meets null, e.g if we gives him char a[] = {'a'}, then it's len may be not 1, but 32, or 40, or whatever any number, maybe even cause some errors.
@6:58 can we make operator
around 14:20 wouldn't you want to use braces for constructor initialization instead of parentheses?
Thank you, very well explained.
Nice explanation, awesome . Excellent work.
Awesome Video .. All concepts well explained...!
At 8:04 he's using a "0" for null terminator instead of "
". why did that work? how is th string terminator defined?
youre a great teacher, thanks
haha ChArno! Bro you are hilarious! Really like the series!!
This was a quality lesson
I just tried this technique
and it work for object on the heap too..
so now I realized const reference is used when the object we want to use
does not need to be changed..
although it is const it's value can be assigned to another variable like std:: vector or array
At 8:02 that would make no difference, because without terminating null we have no way of knowing the string length. strlen() actually keeps counting bytes until (char)0.
How can I distinguish if the constructor in the instance you write is a copy constructor rather than a constructor with parameters? I feel a bit confused.
A copy constructor explicitly pulls values from an existing class object (i.e. other) to create a copy it.
A typical constructor simply creates a new object instance of a class.
why do you set m_Buffer as a pointer but not m_Size?
Amazing explanation ❤️
Doesn't strlen assume null termination? So does code added after 7:50 really provide any robustness to strings without null termination?
@12:50 ok so when i write
String name="anybody";
String anotherName=name;
this means a shallow copy only i.e only copy the pointer to the object but not the object itself
so basically when i write
String name;
is this actually a pointer to a "String" object? on the stack?
now realizes that copy constructor is useful when you want to copy object on the heap i.e when you call "new " keyword if its on the stack there is no problem but the problem is on the heap which is when one of the objects involved in the copying process dies, another object will get reference to an object that already being deallocated..so you must provide your own deep copy using memcpy() function to copy the objects/value to another memory address so when one object get deallocated another object being copied still lives
Thank you Charno, I have learned a lot from you : )
Fantastic content!!!!
Cherno you've said that if you can't be sure the string is null terminated, then just plop in a zero at the end of the string.
But IIRC strlen() makes that assumption for you so the deliberately plopping in a zero at the end by you is irrelevant really, 7:55
hey youre really good at explaining things cheers!
Very confused on why 7:13 works. Since he's pushing a char pointer into the ostream but never derefences it?
Great explanation. Thank you!
The action is starting!
This is a lifesaver
Your tutorials are amazingly well done, and helped me a lot, thanks man!
¡Happy day, Cherno!
I've finally cracked the code. 0.5x Cherno is Cherno on his third bottle of wine...
what is the m_ before variable names ? Is that a standard way of naming variables?
Yes, the m_ means the variable is a member of the class, it's just a convention, just like s_ variables means they are static