Copying and Copy Constructors in C++

แชร์
ฝัง
  • เผยแพร่เมื่อ 20 มิ.ย. 2024
  • Patreon ► / thecherno
    Twitter ► / thecherno
    Instagram ► / thecherno
    Discord ► thecherno.com/discord
    In this video we're talking about copying in C++. Copying objects (and data) is commonly necessary in C++, and to properly facilitate that for our custom types, we need to add something called a copy constructor, which performs a deep copy of our object, if one is necessary. Something called a "(copy) assignment operator" is also sometimes necessary, but we'll talk about that in another video. Copying is not free however, and can slow down your program, so try and avoid it if possible.
    Series Playlist ► • C++
    Thank you to the following Patreon supporters:
    - Samuel Egger
    - Dominic Pace
    Gear I use:
    -----------------
    BEST laptop for programming! ► geni.us/pakTES
    My FAVOURITE keyboard for programming! ► geni.us/zNhB
    FAVOURITE monitors for programming! ► geni.us/Ig6KBq
    MAIN Camera ► geni.us/t6xyDRO
    MAIN Lens ► geni.us/xGoDWT
    Second Camera ► geni.us/CYUQ
    Microphone ► geni.us/wqO6g7K

ความคิดเห็น • 412

  • @Sokar599
    @Sokar599 5 ปีที่แล้ว +1178

    finally a series on youtube I don't have to put on 2x speed lol

    • @fupopanda
      @fupopanda 5 ปีที่แล้ว +52

      Agree. Watching on 1.5x speed. Can't go higher.

    • @KostasOreopoulos
      @KostasOreopoulos 5 ปีที่แล้ว +29

      I am really curious If this is filmed at that speed. It is insanely fast

    • @canadianblitz3468
      @canadianblitz3468 5 ปีที่แล้ว +9

      Up until episode 30 or so I was watching at 2x speed just so i can get back to the opengl series

    • @ondrejvencovsky6834
      @ondrejvencovsky6834 4 ปีที่แล้ว +50

      I'm at 50% speed and finally I understand he speaks english...

    • @macroxela
      @macroxela 4 ปีที่แล้ว +3

      Still watching at 2x speed. Otherwise he would be too slow

  • @dkrec2486
    @dkrec2486 6 ปีที่แล้ว +620

    We're so lucky this C++ series are free x)

    • @aelthalyste6692
      @aelthalyste6692 6 ปีที่แล้ว +25

      Until he realises he can buy a t-rex with his course money if it wasnt free.

    • @laurentiustefan398
      @laurentiustefan398 5 ปีที่แล้ว +17

      then again asking 10$ for this course wouldn't be all that much

    • @hitlard5305
      @hitlard5305 5 ปีที่แล้ว +15

      Laurentiu Stefan it is for some people who just want to learn

    • @raymondyoo5461
      @raymondyoo5461 5 ปีที่แล้ว +3

      absolutely

    • @tamriel_x
      @tamriel_x 4 ปีที่แล้ว +4

      @@hitlard5305 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..

  • @matthewwilson4592
    @matthewwilson4592 5 ปีที่แล้ว +352

    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.

    • @felixkimutai8478
      @felixkimutai8478 5 ปีที่แล้ว +11

      I am worried, he's too fast

    • @marindraganov8765
      @marindraganov8765 3 ปีที่แล้ว +4

      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 :)

    • @this_is_mac
      @this_is_mac 3 ปีที่แล้ว +4

      @@marindraganov8765 If I don't understand something, I keep repeating it

    • @pierfrancescopeperoni
      @pierfrancescopeperoni 2 ปีที่แล้ว +4

      @@this_is_mac While loop?

    • @g4fly4ever8
      @g4fly4ever8 2 ปีที่แล้ว +2

      @@pierfrancescopeperoni
      while(understanding == false){
      ReplayVideo();
      }

  • @muneebj.4010
    @muneebj.4010 3 ปีที่แล้ว +28

    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

  • @lored6811
    @lored6811 4 ปีที่แล้ว +107

    17:48 Little did he know it would take him 3 More Years...

    • @so7am96
      @so7am96 4 ปีที่แล้ว +9

      lol! me too, I actually watched the l, r values first

    • @Strategic.
      @Strategic. 2 ปีที่แล้ว

      lol

  • @Plasticcaz
    @Plasticcaz 6 ปีที่แล้ว +109

    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.

    • @TheCherno
      @TheCherno  6 ปีที่แล้ว +58

      Yes, we'll get into move semantics eventually. :)

  • @rohitsrivastava4775
    @rohitsrivastava4775 6 ปีที่แล้ว

    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.

  • @bonehelm
    @bonehelm 3 ปีที่แล้ว +8

    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.

  • @mikedoeren5960
    @mikedoeren5960 ปีที่แล้ว +5

    I've been rewatching this series just for fun, and as always the videos are excellent, informative, and concise.
    Thanks!

  • @reptilicusrex4748
    @reptilicusrex4748 ปีที่แล้ว

    I recently found these C++ videos on YT. They're excellent. Thanks for the effort Cherno.

  • @fishyperil2153
    @fishyperil2153 6 ปีที่แล้ว +87

    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

    • @MsJavaWolf
      @MsJavaWolf 5 ปีที่แล้ว +6

      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.

    • @letranminhkhoa7492
      @letranminhkhoa7492 3 ปีที่แล้ว

      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"

  • @gopapriyajena8630
    @gopapriyajena8630 2 ปีที่แล้ว +5

    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

  • @seungminlee9793
    @seungminlee9793 4 ปีที่แล้ว +1

    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.

  • @AmitParopkari
    @AmitParopkari 2 ปีที่แล้ว

    this cleared concept of shallow vs deep copy, copy constructor, along with operator overloading & importance of pass by reference, brilliant!

  • @abdulbasir906
    @abdulbasir906 ปีที่แล้ว

    This is one of the greatest content I have seen on C++ copy constructors...Thanks Cherno

  • @nathannlatimore7863
    @nathannlatimore7863 3 ปีที่แล้ว

    This was a really comprehensive tutorial. Thank you!!

  • @BT-fj9ek
    @BT-fj9ek 3 ปีที่แล้ว

    I am new to C++ and your tutorial just save my life, thanks a lot!

  • @danielashmeadwright
    @danielashmeadwright 6 ปีที่แล้ว

    Excellent example, really clear and concise, well done.

  • @imrankhanrahat6031
    @imrankhanrahat6031 5 ปีที่แล้ว

    Thanks for making a good example. It cleared Copy constructor, Deep/Shallow copy and reference.

  • @greatbullet7372
    @greatbullet7372 6 ปีที่แล้ว +3

    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

    • @rickyjoebobby1
      @rickyjoebobby1 4 ปีที่แล้ว

      no kidding, i havent seen many but these are high quality c++ videos

  • @espressothoughts
    @espressothoughts 5 ปีที่แล้ว

    Great job with this series!!

  • @onegamingmoose
    @onegamingmoose 6 ปีที่แล้ว +175

    Charno - No char for you

  • @zjfjack
    @zjfjack 4 ปีที่แล้ว

    Such a fantastic lesson! Second time to review this.

  • @jpack61108
    @jpack61108 2 ปีที่แล้ว

    ive said this before, and ill say it again.. this is one of the most informative code channels on youtube.

  • @mohammednihad6755
    @mohammednihad6755 6 ปีที่แล้ว +6

    this is the most interesting episode in the series :)

  • @asadanees781
    @asadanees781 5 ปีที่แล้ว

    Nice explanation, awesome . Excellent work.

  • @williamchamberlain2263
    @williamchamberlain2263 5 ปีที่แล้ว

    Great summary, excellent, simple examples

  • @_DarkKnight2301_
    @_DarkKnight2301_ 3 ปีที่แล้ว

    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.

  • @jahmurlopez379
    @jahmurlopez379 4 ปีที่แล้ว +1

    Thank you so much for helping with that piece of code for 14:32

  • @roberttoyonaga171
    @roberttoyonaga171 5 ปีที่แล้ว

    Thank you. That was super helpful!

  • @abdulrahmanzaytoun3384
    @abdulrahmanzaytoun3384 3 ปีที่แล้ว +1

    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.

  • @patrickes4540
    @patrickes4540 4 ปีที่แล้ว

    Great explanation. Thank you!

  • @overclockk
    @overclockk 4 ปีที่แล้ว +4

    Just want to say thanks for preparing me for my job interview.

  • @whiteHorse11011
    @whiteHorse11011 2 ปีที่แล้ว

    Thank You. This was an awesome video on c++ concepts.

  • @phicoding7533
    @phicoding7533 ปีที่แล้ว

    Congrats on 500K subs man !

  • @tobiaslauss8200
    @tobiaslauss8200 ปีที่แล้ว

    Thank you, very well explained.

  • @disekjoumoer
    @disekjoumoer 2 ปีที่แล้ว +3

    Man, this series is good. Fast, to the point and makes me feel like I've just sniffed 20 grams of speed.

  • @93davve93
    @93davve93 6 ปีที่แล้ว +2

    Great video!

  • @Rok3y
    @Rok3y ปีที่แล้ว

    You sir are a very good, thanks for these series!

  • @johntera4958
    @johntera4958 2 ปีที่แล้ว

    thanks alot man, you are the best. for me this is heavy stuff alr, but you make me so easy to understand.

  • @TarunKumarSaraswat
    @TarunKumarSaraswat 4 ปีที่แล้ว

    Amazing explanation ❤️

  • @MegtaBubble
    @MegtaBubble 6 ปีที่แล้ว +1

    The action is starting!

  • @MinMorts
    @MinMorts 4 ปีที่แล้ว

    hey youre really good at explaining things cheers!

  • @pwlegolas3
    @pwlegolas3 4 ปีที่แล้ว

    Awesome Video .. All concepts well explained...!

  • @TKcKoucher
    @TKcKoucher ปีที่แล้ว

    Fantastic content!!!!

  • @hosseinbiniaz9379
    @hosseinbiniaz9379 ปีที่แล้ว

    probably the best cpp video it covers so many things haha

  • @wack1305
    @wack1305 2 ปีที่แล้ว

    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

  • @chenjin6407
    @chenjin6407 3 ปีที่แล้ว

    Thank you Charno, I have learned a lot from you : )

  • @Quancept
    @Quancept 3 ปีที่แล้ว

    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 :)

  • @ehsmou3411
    @ehsmou3411 4 ปีที่แล้ว

    That is awesome video!

  • @MetalCrotchGuy
    @MetalCrotchGuy 6 ปีที่แล้ว +65

    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.

    • @Steve-gi2yj
      @Steve-gi2yj 4 ปีที่แล้ว

      yes that worked for me to instead of his way, thanks :)

    • @AntonioAstorino
      @AntonioAstorino 4 ปีที่แล้ว

      Agreed

    • @JohnnyThund3r
      @JohnnyThund3r 4 ปีที่แล้ว +5

      Kinda glad he did it wrong though, the extra steps helped me understand it better and reading the comments gives one expertise.

    • @vesk4000
      @vesk4000 ปีที่แล้ว

      Yeah I got confused about this exact thing.

  • @intjengineering
    @intjengineering 2 ปีที่แล้ว

    Thanks for this video! It is amazing.
    Greetings from Germany!

  • @aleksandarfranc1094
    @aleksandarfranc1094 5 ปีที่แล้ว

    haha ChArno! Bro you are hilarious! Really like the series!!

  • @thesanctuary225
    @thesanctuary225 5 ปีที่แล้ว +4

    C++ is a great language.
    I admire sir. Bijarn Stroustrup as well as sir. Dennis Ritchie.

  • @autumnleaf8483
    @autumnleaf8483 2 ปีที่แล้ว

    I love the humor this man has.

  • @bradleymclean2018
    @bradleymclean2018 ปีที่แล้ว

    this video is still helpful in 2022. Thanks a bunch

  • @doolee5704
    @doolee5704 7 หลายเดือนก่อน

    youre a great teacher, thanks

  • @shawkontzu3990
    @shawkontzu3990 2 ปีที่แล้ว

    best video explaining copy and deepcopy

  • @ardeipopa
    @ardeipopa 5 ปีที่แล้ว

    Very helpful. Also note that you will make a copy when you return a String object

  • @zeynepsedabirinci1409
    @zeynepsedabirinci1409 6 ปีที่แล้ว

    Awesome, Thanks!

  • @LordFers
    @LordFers 6 ปีที่แล้ว

    ¡Happy day, Cherno!

  • @samsawesomeminecraft
    @samsawesomeminecraft 5 ปีที่แล้ว +3

    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

  • @OnlyfansCustomerSupport
    @OnlyfansCustomerSupport 2 ปีที่แล้ว

    Nice one :) i get the ideas of what that actualy does far better Then in highscool explanation

  • @gavinw77
    @gavinw77 6 ปีที่แล้ว

    Great episode.

  • @crankyunicorn4423
    @crankyunicorn4423 4 ปีที่แล้ว +1

    this is very good information

  • @abhisheksa6635
    @abhisheksa6635 10 หลายเดือนก่อน

    Nice explanation.

  • @akiyprum
    @akiyprum ปีที่แล้ว

    Awesome video

  • @enesk2120
    @enesk2120 6 ปีที่แล้ว

    Very nice tutorial

  • @yavuzselimcagan5233
    @yavuzselimcagan5233 2 ปีที่แล้ว

    Fantastic!

  • @Maceta444
    @Maceta444 2 ปีที่แล้ว

    This was a quality lesson

  • @buddhasarchive8385
    @buddhasarchive8385 3 ปีที่แล้ว

    Great video

  • @aungkyawkyaw9114
    @aungkyawkyaw9114 3 หลายเดือนก่อน

    just excellent!

  • @mehmetedex
    @mehmetedex ปีที่แล้ว

    detail is rich, pace is balanced, a sub is gained

  • @thesanctuary225
    @thesanctuary225 5 ปีที่แล้ว +7

    Creation of "Reference(&)" is one of the good improvement of C++ comparing with C.
    Reference gives more "memory efficiency" to us.

    • @nonnullptrhuman504
      @nonnullptrhuman504 2 ปีที่แล้ว

      Also if the function accept reference you don't have to check if the argument is null or not

    • @thewelder3538
      @thewelder3538 ปีที่แล้ว

      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.

  • @rcookie5128
    @rcookie5128 6 ปีที่แล้ว +1

    really helpfull stuff :)

  • @patrickg2416
    @patrickg2416 3 ปีที่แล้ว +1

    Deep Object.. Shallow Copy.. I saw that look! So many great analogies to make lol

  • @FadeStrategy
    @FadeStrategy 3 ปีที่แล้ว

    This is a lifesaver

  • @mohamedmellouky8498
    @mohamedmellouky8498 3 ปีที่แล้ว

    Just WoW
    Thank you

  • @voynich7119
    @voynich7119 2 ปีที่แล้ว +3

    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 :)

  • @ahmeddeghady4510
    @ahmeddeghady4510 4 ปีที่แล้ว

    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

  • @John2137Paul
    @John2137Paul 4 ปีที่แล้ว

    Your tutorials are amazingly well done, and helped me a lot, thanks man!

  • @krazyolie
    @krazyolie 3 ปีที่แล้ว +2

    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.

  • @elijahwoelbing6360
    @elijahwoelbing6360 2 ปีที่แล้ว

    THanks Charno

  • @serkanozturk4217
    @serkanozturk4217 ปีที่แล้ว +17

    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.

  • @IgorSantarek
    @IgorSantarek 5 ปีที่แล้ว

    You have my sub.

  • @mytech6779
    @mytech6779 2 ปีที่แล้ว +2

    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.)

  • @lfernandorg
    @lfernandorg 3 ปีที่แล้ว

    Hey Yan, I'm following your channel for about a few days, and I'm loving your videos about C++ and I wanna know if you have a Github of projects in C++ or maybe you know of some Githubs with projects in C++, I wanna look at the code to learn more programming technics.

  • @darkpikachu_.
    @darkpikachu_. 3 ปีที่แล้ว

    Shin Lim does a good job teaching C++.

  • @senemyildiz.
    @senemyildiz. 3 ปีที่แล้ว

    You are talking so fast. but your style is very clear. Thanks for sharing.

  • @accessdenied9393
    @accessdenied9393 2 ปีที่แล้ว

    Awesome BUT so fasssst! I have to watch the video many times to better understand. Anyways you are still my professor

  • @LowLevelLemmy
    @LowLevelLemmy ปีที่แล้ว

    I love you Charno

  • @chainonsmanquants1630
    @chainonsmanquants1630 3 ปีที่แล้ว

    Thanks

  • @ricardoffrancisco
    @ricardoffrancisco 6 ปีที่แล้ว

    Any idea when you'll be able to get to move semantics? BTW great job with this c++ series!

  • @knooiwark
    @knooiwark 5 ปีที่แล้ว

    That cactus, watch out for your hands ;) thanks for explaining!

  • @astaghfirullahalzimastaghf3648
    @astaghfirullahalzimastaghf3648 2 ปีที่แล้ว +1

    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

  • @rohitrajak5128
    @rohitrajak5128 3 ปีที่แล้ว

    Way to go Charno

  • @ivanleon6164
    @ivanleon6164 3 ปีที่แล้ว

    thanks Charno.

  • @georgei2480
    @georgei2480 4 ปีที่แล้ว +1

    @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!

  • @lysdexic9129
    @lysdexic9129 6 ปีที่แล้ว

    is it suitable to simply use 'unsigned int' to cater for functions like strlen which return size_t. I believe most implementations define size_t as a typedef of unsigned int.

  • @VeraxonHD
    @VeraxonHD 4 ปีที่แล้ว +1

    God, I wish my lecturer explained this like you did...