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

  Рет қаралды 249,498

The Cherno

The Cherno

7 жыл бұрын

Patreon ► / thecherno
Twitter ► / thecherno
Instagram ► / thecherno
Slack ► slack.thecherno.com
Discord ► / discord
Series Playlist ► • C++
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

Пікірлер: 265
@samdavepollard
@samdavepollard 3 жыл бұрын
watched this earlier today and have just written my first constructor initializer list i confess, i'm feeling pretty gangster right now
@Plasticcaz
@Plasticcaz 7 жыл бұрын
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 жыл бұрын
Exactly, needs better documentation.
@LoxagosSnake
@LoxagosSnake 6 жыл бұрын
Lost it at the closed captions. "Hello guys my name is a cheddar"
@FoxSensei
@FoxSensei 5 жыл бұрын
Cheddar Bob
@olliert4840
@olliert4840 4 жыл бұрын
@@nijucow i ALWAYS hear: " My name is 'Ocherno' "
@tedchirvasiu
@tedchirvasiu 3 жыл бұрын
I always hear it: "My name is the Cyano"
@1Naif
@1Naif 7 жыл бұрын
Also you cant initialize *const* members without using "Member initializer".
@SrogaPoziomka
@SrogaPoziomka 5 жыл бұрын
I was going to write same thing. :)
@annahakobian7371
@annahakobian7371 5 жыл бұрын
if I'm not mistaken reference types also must be initialized in the initializer list
@venkateswarans1012
@venkateswarans1012 5 жыл бұрын
What about static .?
@patrikjankovics2113
@patrikjankovics2113 5 жыл бұрын
@@venkateswarans1012 Well, those will be initialized by default I think, because you can access them without creating an object
@jatinchadha7740
@jatinchadha7740 4 жыл бұрын
Basically all members which should be initialized at time of declaration should be written in initializer list like const , references etc.
@DaRealPielover1987
@DaRealPielover1987 7 жыл бұрын
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.
@hexi3064
@hexi3064 3 жыл бұрын
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.)
@drkerberos
@drkerberos 3 жыл бұрын
Mind blown @The Cherno. As I said in a earlier video and will say now you are the best C++ teacher and course on KZfaq. 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.
@TheKingofkatz
@TheKingofkatz 5 жыл бұрын
Incredible video series that will remain relevant for years to come. Nice work man, appreciate it.
@passionfruit7617
@passionfruit7617 2 жыл бұрын
confirmed
@allenvicencio5156
@allenvicencio5156 7 жыл бұрын
Wanted to say thanks! Your videos are great and are a huge help to me in understanding C++.
@samarthsrivastava6220
@samarthsrivastava6220 6 жыл бұрын
@TheChernoProject Man! You rock!!!. I was having trouble understanding this but you made it so simple with ur examples. Thanks!
@BOTHLine
@BOTHLine 7 жыл бұрын
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!
@wearyadventurer404
@wearyadventurer404 3 жыл бұрын
"hey little guys my name is a chadder and welcome back to my say plus plus series" xD
@BlackJar72
@BlackJar72 6 жыл бұрын
Yay! I finally am back online and can catch up with these awesome videos!
@b_01_aditidonode43
@b_01_aditidonode43 3 ай бұрын
amazing explaination and that is amazing effect there when you said like and the like button actually glowed , woah mindblown
@MiddleCross378
@MiddleCross378 4 жыл бұрын
Thank you, exactly what I was looking for.
@h.hristov
@h.hristov 7 жыл бұрын
Thanks for the daily uploads :D
@mamoudgad4210
@mamoudgad4210 Жыл бұрын
I just want to thanks for this great content one of the best c++ courses on KZfaq
@legendarytwister3656
@legendarytwister3656 2 ай бұрын
i didnt know that. thanks, ive watched alot of your videos you are doing great work. cheers
@asterisk4424
@asterisk4424 2 жыл бұрын
Dude thank you so much I love your videos
@TheSunscratch
@TheSunscratch 7 жыл бұрын
Photo on the wall is awesome!
@barellevy6030
@barellevy6030 6 жыл бұрын
Appreciate you! Great content! Thank you!
@yavuzselimcagan5233
@yavuzselimcagan5233 2 жыл бұрын
It's really good to learn that.
@adrianhurtado8323
@adrianhurtado8323 2 жыл бұрын
Thank you for this!
@SruVekDiaries
@SruVekDiaries 5 жыл бұрын
Ur videos are awesome bro..Keep it up...u r genius
@dhu1090
@dhu1090 2 жыл бұрын
YOU ARE AMAZING!
@eruston
@eruston 6 жыл бұрын
Great video, very easy to understand, bought the book: ‘effective c++ third ed.’ Great compliment to that book.
@lucha6262
@lucha6262 4 жыл бұрын
This video should come before the virtual functions video!
@lucha6262
@lucha6262 4 жыл бұрын
Greatgreat video though, I will forever use this from now on!
@joshs2475
@joshs2475 7 жыл бұрын
Don't forget Member Initializer Lists can also be used for initializing const member variables as well!
@deltarambo6230
@deltarambo6230 4 жыл бұрын
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.
@toast_on_toast1270
@toast_on_toast1270 2 жыл бұрын
Love you man, C++ for life
@ghostradiodelete
@ghostradiodelete 6 жыл бұрын
"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.
@gamelovers4974
@gamelovers4974 11 ай бұрын
You are the best cherno.
@meh1672
@meh1672 7 жыл бұрын
These video's are the best! :D
@jamessun7058
@jamessun7058 9 ай бұрын
Thanks!
@pawankumarmeena6737
@pawankumarmeena6737 5 жыл бұрын
you are my hero
@tessa10001
@tessa10001 4 жыл бұрын
amazing, thanks
@mryup6100
@mryup6100 4 жыл бұрын
This is amazing. Code changer for sure y'all!
@winniethedictator2777
@winniethedictator2777 2 жыл бұрын
thank you
@Nick-lx4fo
@Nick-lx4fo 3 жыл бұрын
Thank you
@zfighter3
@zfighter3 7 жыл бұрын
Holy cow. It's like a constant stream of videos!! I use some of your videos as reference for my high school classes. Cheers!
@vyomraj3389
@vyomraj3389 3 жыл бұрын
Wow thanks!
@qandos-nour
@qandos-nour 4 жыл бұрын
thank you you are the best
@krec348
@krec348 7 жыл бұрын
YES! DAILY VIDEOS :D
@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
@joseponce6250
@joseponce6250 2 жыл бұрын
brillant!!
@valentinamerturi2330
@valentinamerturi2330 5 жыл бұрын
greate video!
@georgei2480
@georgei2480 3 жыл бұрын
Mr. Cherno . You are my hero
@moazelsawaf2000
@moazelsawaf2000 4 жыл бұрын
Thanks a lot sir
@mattgraves3709
@mattgraves3709 3 жыл бұрын
Very cool, I like this style vs Java
@meelz812
@meelz812 2 жыл бұрын
Cherno does not miss
@ohmnamo7056
@ohmnamo7056 4 жыл бұрын
wow ...gr8 explanation.....thanks a lot...
@Karolis554
@Karolis554 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 жыл бұрын
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.
@amrtcpp6203
@amrtcpp6203 4 жыл бұрын
thanks man , you save me
@marvel438
@marvel438 4 жыл бұрын
Too awesome.
@stormwaker
@stormwaker 6 жыл бұрын
I cannot think of another KZfaqr with such a high likes to dislikes ratio under his videos. Is this how perfection looks like?
@teosurch
@teosurch 4 ай бұрын
Thank you! Finally got the new constructor syntaxis ( a(a1) like instead of this->a = a1 );
@sing759
@sing759 5 жыл бұрын
awesome
@farsanrashid5601
@farsanrashid5601 6 жыл бұрын
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 Жыл бұрын
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.
@turdle2767
@turdle2767 Жыл бұрын
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.
@pedramgh2998
@pedramgh2998 4 жыл бұрын
Thanks 😊 🙏🌹❤️
@NeZversSounds
@NeZversSounds 4 жыл бұрын
Another frustration explained!
@laad
@laad 7 жыл бұрын
Awesome
@hpsmash77
@hpsmash77 3 жыл бұрын
i can hear a robot talking in background lol confirmed cherno is not a human
@AdityaPrasad007
@AdityaPrasad007 5 жыл бұрын
3:17 why why!! thank you for asking that. wow... performance issues. good enough for me.
@varuntaneja7073
@varuntaneja7073 4 жыл бұрын
You used this in one of your previous videos (maybe the virtual functions) and I was so damn confused . ps : I get it now
@sergeyklassen9696
@sergeyklassen9696 7 жыл бұрын
Great video! Did you change the audio settings? Sounds different.
@BernardoSOUSAstudent
@BernardoSOUSAstudent 3 жыл бұрын
That.... was totally new to me.
@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.
@rajakandukuri8509
@rajakandukuri8509 4 жыл бұрын
this nice trick made me get rid of heap alloc.
@Nicolas-gq9vu
@Nicolas-gq9vu 7 жыл бұрын
Nice video :')
@dr3mro
@dr3mro 5 жыл бұрын
we need a series of wxwidgets :)
@AbdulMoiz-ho8rx
@AbdulMoiz-ho8rx 2 жыл бұрын
Great
@prometheus8439
@prometheus8439 5 жыл бұрын
you deserve as much as subscribers as PewDiePie
@BatmanBottomG
@BatmanBottomG 3 жыл бұрын
caption really says, hey little guys my name is a cheddar. NOOooOoOoo
@imninja4220
@imninja4220 5 жыл бұрын
in short, constructors assign the variables to a new value while member initialiser list simply initialise them
@flecko5
@flecko5 Жыл бұрын
Good summary
@smileynetsmileynet7922
@smileynetsmileynet7922 3 жыл бұрын
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...
@user-bi1qi8bl9y
@user-bi1qi8bl9y 4 жыл бұрын
Today's hair is also just perfect.
@mytech6779
@mytech6779 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
@ymahmoodi5817
@ymahmoodi5817 4 жыл бұрын
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!
@serkanozturk4217
@serkanozturk4217 Жыл бұрын
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
@jongofett2343
@jongofett2343 4 күн бұрын
this guy is so gay i love it
@adamhendry945
@adamhendry945 Жыл бұрын
Can you please do a video on padding and alignment as well as the pIMPL idiom?
@robinmaes8818
@robinmaes8818 7 жыл бұрын
When you don't use initializer list and you construct a member class twice, does the first instance get destructed when the second one is constructed or does this happen afterwards?
@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.
@shahidk2223
@shahidk2223 7 жыл бұрын
Cherno talk about Trace and Unicode
@popplestones886
@popplestones886 2 жыл бұрын
Do you use inititializer lists just with constructor or can / should you use on regular functions?
@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.
@pranjalbajpai156
@pranjalbajpai156 2 жыл бұрын
Charno !!
@AviPars
@AviPars 2 жыл бұрын
Please do a video kn std containers. Lists and algos like for each
@chiyungchu9463
@chiyungchu9463 3 жыл бұрын
Why not immediate initialize them inside the class instead of inside constructor?
@puppy0cam
@puppy0cam 4 жыл бұрын
What if there is no default constructor and you assign from the body of the initialiser instead of the initialiser list?
@DaemonJax
@DaemonJax Жыл бұрын
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.
@edwinov
@edwinov 2 ай бұрын
I initialised my member loooong ago
@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?
@RoboTricker
@RoboTricker 7 жыл бұрын
I've watched many C++ Tutorials now and this one is far the best! :P I'm still wondering what the three access operators mean (dot, colon and arrow). Maybe that's a good topic for a tutorial ;)
@Hopsonn
@Hopsonn 7 жыл бұрын
Dot is accessing members of an object eg Dog d; dog.age = 10; Arrow is for dereferencing a pointer, aka accessing the variable the pointer is pointing to. Dog dog1; Dog* pDog = &dog; pDog->bark();//Calls bark on the "dog1" object Colon is for accessing classes and functions inside of a namespace, or static variables and functions in classes, or for defining member functions and defining static class variables.
@RoboTricker
@RoboTricker 7 жыл бұрын
Hopson wow, quick and brief. Thanks :)
@gabiold
@gabiold 3 жыл бұрын
@@Hopsonn Little nitpicking: Arrow does not dereference the pointer and access the variable it points to, rather it does that *then* accesses a *member* (or method) of that variable it points to. So technically two operation in one, thus the variable should be of a type with members (or methods), eg. class, struct. So to be consistent with your first example: Dog is a class or struct instance: Dog d; d.age = 10; d2 is a pointer to a Dog instance: Dog *d2 = &d; d2->age = 11; // this arrow op. is just a nicer, shorter form of this: (*d2).age = 11; These last two lines does exactly the same. So a simple dereferencing of d2 is useful to get the Dog instance it points to, without accessing it's member. It is *d2, for example Dog d3 = Dog(*d2); Executing all the above, you'll end up with 2 distinct Dog instances, d and d3 d2 is just a pointer to d d.age is overwritten to 11 trough the pointer. d3 is copied from where d2 points to, so from d, thus d3.age is also 11.
@johnk6598
@johnk6598 3 жыл бұрын
Would default arguments be another way to accomplish this?
@ashtonkusmaul6907
@ashtonkusmaul6907 Жыл бұрын
what if you used like std::string& then would it still douplicate it
@leixun
@leixun 4 жыл бұрын
*My takeaways:* Why should we use member initializer lists 3:10: clean code and speed advantage
@TKcKoucher
@TKcKoucher 2 жыл бұрын
Would it be correct to use member lists to initialize variables in a struct? I'm using a struct to group a bunch of variables (integers, small arrays, etc.) that are going to be filled with data once I read a binary file using .read() from std::ifstream. Even in this case, should I be using a member initializer list instead of initializing these variable inside the constructor?
@arek9430
@arek9430 2 жыл бұрын
Everytime I go for on of your videos I wonder how deep I will go into the rabit hole, because your content is often packed with things I don't know yet xD, edit: this time was smooth.
@lightps5515
@lightps5515 Жыл бұрын
What is the downside of initializing a variable in the header instead of the constructor especially for the primitive data types?
@cubedude76
@cubedude76 Жыл бұрын
Is this also how I should be initializing struct members variables?
Ternary Operators in C++ (Conditional Assignment)
8:01
The Cherno
Рет қаралды 122 М.
lvalues and rvalues in C++
14:13
The Cherno
Рет қаралды 308 М.
1,000 Diamonds! (Funny Minecraft Animation) #shorts #cartoon
00:31
toonz CRAFT
Рет қаралды 39 МЛН
Они так быстро убрались!
01:00
Аришнев
Рет қаралды 1,9 МЛН
Schoolboy - Часть 2
00:12
⚡️КАН АНДРЕЙ⚡️
Рет қаралды 2,5 МЛН
WHY did this C++ code FAIL?
38:10
The Cherno
Рет қаралды 240 М.
Member Initializer Lists | C++ Tutorial
23:10
Portfolio Courses
Рет қаралды 8 М.
Stack vs Heap Memory in C++
19:31
The Cherno
Рет қаралды 560 М.
CONST in C++
12:54
The Cherno
Рет қаралды 398 М.
What is the Difference Between a Pointer and a Reference C++
7:58
Paul Programming
Рет қаралды 426 М.
How to CREATE/INSTANTIATE OBJECTS in C++
13:03
The Cherno
Рет қаралды 239 М.
SOME UNIQUE C++ CODE! // Pacman Clone Code Review
26:42
The Cherno
Рет қаралды 268 М.
OPERATORS and OPERATOR OVERLOADING in C++
12:44
The Cherno
Рет қаралды 367 М.
SINGLETONS in C++
19:16
The Cherno
Рет қаралды 197 М.
you will never ask about pointers again after watching this video
8:03
Low Level Learning
Рет қаралды 2,1 МЛН
1,000 Diamonds! (Funny Minecraft Animation) #shorts #cartoon
00:31
toonz CRAFT
Рет қаралды 39 МЛН