Member Initializer Lists in C++ (Constructor Initializer List)

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

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

  • @samdavepollard
    @samdavepollard 4 года назад +48

    watched this earlier today and have just written my first constructor initializer list
    i confess, i'm feeling pretty gangster right now

  • @1Naif
    @1Naif 7 лет назад +440

    Also you cant initialize *const* members without using "Member initializer".

    • @SrogaPoziomka
      @SrogaPoziomka 6 лет назад +8

      I was going to write same thing. :)

    • @annahakobian7371
      @annahakobian7371 5 лет назад +14

      if I'm not mistaken reference types also must be initialized in the initializer list

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

      What about static .?

    • @patrikjankovics2113
      @patrikjankovics2113 5 лет назад +12

      @@venkateswarans1012 Well, those will be initialized by default I think, because you can access them without creating an object

    • @jatinchadha7740
      @jatinchadha7740 4 года назад +7

      Basically all members which should be initialized at time of declaration should be written in initializer list like const , references etc.

  • @Plasticcaz
    @Plasticcaz 7 лет назад +124

    I didn't realize this actually had performance benefits.
    When I first saw them, I thought they were just a nifty way of writing constructors.

    • @mryup6100
      @mryup6100 4 года назад +21

      Exactly, needs better documentation.

  • @DaRealPielover1987
    @DaRealPielover1987 7 лет назад +206

    Hey Cherno. Just want to say that this series is one of the best I've seen on youtube. I've been in the industry for about a year now but having refreshers like these are always good. Like I haven't actually thought about why I use member initializer lists in years since I've just gotten in the habit of doing so. I'm looking forward to more videos so that I can fully recommend this series to more novice programmers.

  • @LoxagosSnake
    @LoxagosSnake 6 лет назад +165

    Lost it at the closed captions.
    "Hello guys my name is a cheddar"

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

      Cheddar Bob

    • @olliert4840
      @olliert4840 5 лет назад +4

      @@nijucow i ALWAYS hear: " My name is 'Ocherno' "

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

      I always hear it: "My name is the Cyano"

  • @hexi3064
    @hexi3064 4 года назад +33

    Member Initializer List allows you to use references as properites of a class. (Without using it, you cannot do it because references has to have assigned values while being created.)

  • @joshs2475
    @joshs2475 7 лет назад +93

    Don't forget Member Initializer Lists can also be used for initializing const member variables as well!

    • @deltarambo6230
      @deltarambo6230 4 года назад +17

      Basically, all data-members which should be initialized at time of declaration, such as const , references, etc., must be included in the constructor's initializer list.

  • @drkerberos
    @drkerberos 3 года назад +7

    Mind blown @The Cherno. As I said in a earlier video and will say now you are the best C++ teacher and course on RUclips. To the way you describe subjects to asking the biggest question of why you would need to use them and giving an example. To be honest I thought I would never be able to learn programming and actually learning the materials until I went to college and forced myself but I was wrong. I wish I found this channel sooner than I did. Big props to you though in helping everyone and making this playlist. I can't wait to learn more from the rest of the videos and then try and make a simple project later on.

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

    This video should come before the virtual functions video!

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

      Greatgreat video though, I will forever use this from now on!

  • @zfighter3
    @zfighter3 7 лет назад +37

    Holy cow. It's like a constant stream of videos!! I use some of your videos as reference for my high school classes. Cheers!

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

    Incredible video series that will remain relevant for years to come. Nice work man, appreciate it.

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

    Cherno makes both C++ and teaching C++ look easy
    Heck, been reading some Stanley Lippman and that dork just sux ass explaining, and the book is a fucking minotaur maze. While Chemo makes it crystal clear and enjoyable. I just feel like I'm having a great company and we speak same language. I feel so much better watching these. Thank you, Cherno, you bring a lot to this world

  • @allenvicencio5156
    @allenvicencio5156 7 лет назад +5

    Wanted to say thanks! Your videos are great and are a huge help to me in understanding C++.

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

    amazing explaination and that is amazing effect there when you said like and the like button actually glowed , woah mindblown

  • @legendarytwister3656
    @legendarytwister3656 6 месяцев назад +1

    i didnt know that. thanks, ive watched alot of your videos you are doing great work. cheers

  • @BOTHLine
    @BOTHLine 7 лет назад +1

    First of all really thank your for all the videos. Even though the most concepts may be known by a lot of people already, it's interesting to see what happens behind the scenes. For example the Initializer lists. I knew they would be better in terms of performance in some situations.. but I never actually knew why and when especially. I didn't even feel the need to look it up. But I just like to know things like those, so these videos are really interesting and helping me out!
    And I like it, you are not discriminating primitive types nor classes!

  • @farsanrashid5601
    @farsanrashid5601 6 лет назад +2

    Great work! I would like add two things though, I am not really sure why 2:48 "make sure you always initialize your variables in the same order that they are declared in when you declared them as members" If the order of initialization only matters on the order of member declaration when using initialization list it should not matter in which order I initialized them, it would matter if I had not used initializer list and initialized inside curly braces. Second the main reason that initialization by list is better is that it only calls the constructor but if I initialize inside curly braces a copy assignment is performed after the constructor. Scott meyers 55 ways item 4. Again keep up the good work.

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

      You just keep the order the same as your members to not confuse yourself. Try something like Entity:m_x(5),m_y(m_x+1) and flip the order.

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

      i mean, he explicitly states that it could mess up depending on the compiler. and feels like he's mostly encouraging this for good practice.

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

    I just want to thanks for this great content
    one of the best c++ courses on RUclips

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

    Should use uniform initialization '{}' instead of '()' because it will warn on implicit narrowing conversions. '()' will silently allow, for example, an int to be truncated to a char.
    So this is better
    public:
    Entity() : m_Name{"Unknown"}, x{0}, y{0}, z{0}
    { std::cout

  • @matt-g-recovers
    @matt-g-recovers 3 года назад +1

    Very cool, I like this style vs Java

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

    Photo on the wall is awesome!

  • @Karolis554
    @Karolis554 7 лет назад +7

    and also Initializer list is helpfull when you have to initialize "const" variables/objects inside a class, because you can't overwrite const objects with "=" operator :)

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

      Basically, all data-members which should be initialized at time of declaration, such as const , references, etc., must be included in the constructor's initializer list.

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

    Thank you, exactly what I was looking for.

  • @BlackJar72
    @BlackJar72 7 лет назад +1

    Yay! I finally am back online and can catch up with these awesome videos!

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

    @TheChernoProject Man! You rock!!!. I was having trouble understanding this but you made it so simple with ur examples. Thanks!

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

    YOU ARE AMAZING!

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

    Some think that I do not understand is that even after moving m_Example(8) in to initializer list, the Example m_Example is still in line 22, and as Cherno said, because it is in member region it does not mean that it will nor run and create an instance. So, why now does not create an instance!

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

    You are the best cherno.

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

    Love you man, C++ for life

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

    Cherno does not miss

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

    It's really good to learn that.

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

    Personal Notes:
    - Way of constructing objects by assigning members values
    - Not only a coding style, if you don't use that you initialize objects twice , one when declaring the member, and the other one when assigning it to a different object again inside constructor which takes parameters

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

    Great video, very easy to understand, bought the book: ‘effective c++ third ed.’ Great compliment to that book.

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

    Thank you! Finally got the new constructor syntaxis ( a(a1) like instead of this->a = a1 );

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

    So far, I've left initializers out of pnfha, because what I would have had the option to do is make a function with 2 bodies. Maybe it wouldn't be that way later in development though...

  • @wearyadventurer404
    @wearyadventurer404 3 года назад +6

    "hey little guys my name is a chadder and welcome back to my say plus plus series" xD

  • @h.hristov
    @h.hristov 7 лет назад +4

    Thanks for the daily uploads :D

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

    Dude thank you so much I love your videos

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

    You didn't mention that you can also give the intializer list a private static function to initialize a member variable. Sometimes you need to do something more complicated than just a simple assignment. Maybe that's a new language feature in 14, 17, or 20. Dunno. You can also give it a constructor for a nested class or whatever. The initializer list is kinda clunky tbh but I feel forced to use it, but the only real downside is that when using the initializer list AND you want to use the constructor for other things to set up the class without using a secondary manually called init function, you're FORCED to implement it in the header instead of the source file so you can't hide the implementation details... holy run-on sentence, Batman. That's a weird design decision... flaw, if you ask me. Some other stuff is also weird... like you can't use a static function for array initialization in the initialization list. You. Just. Can't.

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

    3:17 why why!! thank you for asking that. wow... performance issues. good enough for me.

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

    Doesn't "... :m_Example(Example(8)) ..." Implicitly use the copy constructor? It hasn't been overloaded with a cout so it doesn't appear in the terminal.

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

    you deserve as much as subscribers as PewDiePie

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

    Thank you for this!

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

    what if you used like std::string& then would it still douplicate it

  • @Nick-lx4fo
    @Nick-lx4fo 4 года назад

    Thank you

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

    Why not immediate initialize them inside the class instead of inside constructor?

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

    you are my hero

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

    I cannot think of another RUclipsr with such a high likes to dislikes ratio under his videos. Is this how perfection looks like?

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

    Would default arguments be another way to accomplish this?

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

    Mr. Cherno
    . You are my hero

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

    This is amazing. Code changer for sure y'all!

  • @qandos-nour
    @qandos-nour 4 года назад

    thank you
    you are the best

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

    I am quite sure, that if you try this in Release mode, then you get the same result with init list and without.

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

    Appreciate you!
    Great content!
    Thank you!

  • @MrDivad006
    @MrDivad006 6 лет назад +4

    5:55, this is so confusing. Why would it run that code before the code in the constructor?

    • @Netrole
      @Netrole 4 года назад +8

      It runs the code so the variables you are assigning values to in the constructor actually exist

  • @ghostradiodelete
    @ghostradiodelete 7 лет назад +1

    "if we....were to....move this...." haha thanks William Shatner, that was very helpful. In all seriousness though I really dig these videos and am looking forward to the opengl series.

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

    you can't initialize const and reference members without the initializer, ty for the vid very helpful :)

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

    Hello I have a question can we use c++ for web application's the part of backend ? can you teach how to create web-backend or desktop applications or how can we use c++ for mobile (some percentage) please give me answer.

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

      Look at webassembly

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

    brillant!!

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

    amazing, thanks

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

    Wow thanks!

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

    Is this also how I should be initializing struct members variables?

  • @leixun
    @leixun 4 года назад +4

    *My takeaways:*
    Why should we use member initializer lists 3:10: clean code and speed advantage

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

    Thanks!

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

    wow ...gr8 explanation.....thanks a lot...

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

    I just realized his voice sounds exactly like the character Lawrence (Prince Naveed's butler) in the Disney movie, the princess & the frog.

  • @krec348
    @krec348 7 лет назад +4

    YES! DAILY VIDEOS :D

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

    What is the downside of initializing a variable in the header instead of the constructor especially for the primitive data types?

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

    Ur videos are awesome bro..Keep it up...u r genius

  • @imninja4220
    @imninja4220 6 лет назад +4

    in short, constructors assign the variables to a new value while member initialiser list simply initialise them

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

      Good summary

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

    Another frustration explained!

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

    this nice trick made me get rid of heap alloc.

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

    Please do a video kn std containers. Lists and algos like for each

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

    "I don't discriminate between primitive type and class type"
    I'll cheers to that. (I code in Python)

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

    Can you please do a video on padding and alignment as well as the pIMPL idiom?

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

    thanks man , you save me

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

    Plus there is the case where your class member has NO default constructor and requires parameters passed to create. Then you NEED the initialiser list.

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

    If the default constructor initializes a member variable to some default value. Wouldn't it be simpler to just assign the default value when declaring it?

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

    what does const std::string& GetName() means? why did we put the & sign in the return type ?

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

      @Peterolen can we say that all what references do is to avoid unnecessary copies ?

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

      Wouldn’t this be an issue since any changes to the “outside” string will cause changes in the initialized class? Is the normal, copy-Val a safer option for classes?

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

    A heads up: you can't initialize inherited values this way unless you redefine them.

  • @dr3mro
    @dr3mro 5 лет назад +3

    we need a series of wxwidgets :)

  • @我有一个朋友-i2u
    @我有一个朋友-i2u 4 года назад +1

    Today's hair is also just perfect.

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

    What if there is no default constructor and you assign from the body of the initialiser instead of the initialiser list?

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

    That.... was totally new to me.

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

    🔴HELP :
    I have 3 constructors : a default constructors with no parameters, a constructor with a parameter, and a copy constructor
    the constructor with the parameter works fine. the copy constructor works fine,
    but for the default constructor, C++ says "expression must have class type but it has type "ClassName (*)()""
    what is going on and how to fix it ?

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

    i can hear a robot talking in background lol
    confirmed cherno is not a human

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

    You MUST use initializer list if you have CONST member variables. Complied error if not

  • @dogaruionut-beniamin1261
    @dogaruionut-beniamin1261 2 года назад

    Also, if a default constructor is not available you can't even avoid using the initializer list.

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

    Great video! Did you change the audio settings? Sounds different.

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

    great video but i had to turn the play back speed down. For 4:35 onwards you just put it in turbo mode and blew by it. a little confusing...

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

    These video's are the best! :D

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

    5:39
    i don't understand that part. I'm not getting a value when i'm using string

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

    I don't quite get it. Is this just if you use an overloaded constructor in addition to the default constructor? Or should you just use it always?

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

    Do you use inititializer lists just with constructor or can / should you use on regular functions?

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

    I'm a bit confused about 4:10. You're saying the member will be constructed twice: once in the default constructor, and again with the "Unknown" string value. Where I'm confused is that the default constructor is already being used in your example to set the string to "Unknown" already. So is there a second "hidden" default constructor some where else?

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

      So, to explain it as best I can:
      Every class has a default constructor. If you don't implement one on your own there will be an empty one there. Every member class variables that an object has are instantiated via default constructor when the object is instantiated, that is before the code inside of that object's constructor is ran, but after it's initializer list, unless initialized already.
      If you've hidden the constructor of the class you are initializing (by making it private or protected), or if you have member variables that are constants or reference types you have to initialize them either in the initializer list or in their declaration (doing it at declaration time doesn't allow you to pass them any parameters so be wary of that).

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

    why do you pass it in by reference into the constructor?

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

    caption really says, hey little guys my name is a cheddar.
    NOOooOoOoo

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

    Too awesome.

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

    6:39
    What if theres another Constructor for Entity which takes Example object as a parameter , and i want to define m_Example as the Example object on the parameter.
    the code, looks like this
    Entity(Example x) : m_Example(x) {}
    Is it possible?
    Or is it gonna throw error instead?
    If it is possible, what if the Example class also has constructor that takes Example object as it parameter ( Example(Example e) {} ) ?

  • @Anton-sz6ef
    @Anton-sz6ef 3 года назад

    Why not do this ?
    struct exemple{
    exemple(int x){
    nr n(x);
    }
    };
    Can someone explain ? I know this is old. Also, nr just has a constructor that gives some number the value x, like in the video...