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

  Рет қаралды 262,509

The Cherno

The Cherno

Күн бұрын

Пікірлер: 273
@samdavepollard
@samdavepollard 4 жыл бұрын
watched this earlier today and have just written my first constructor initializer list i confess, i'm feeling pretty gangster right now
@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.
@ChromoXD
@ChromoXD 2 ай бұрын
*Charno
@LoxagosSnake
@LoxagosSnake 7 жыл бұрын
Lost it at the closed captions. "Hello guys my name is a cheddar"
@FoxSensei
@FoxSensei 6 жыл бұрын
Cheddar Bob
@olliert4840
@olliert4840 5 жыл бұрын
@@nijucow i ALWAYS hear: " My name is 'Ocherno' "
@tedchirvasiu
@tedchirvasiu 4 жыл бұрын
I always hear it: "My name is the Cyano"
@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.
@drkerberos
@drkerberos 4 жыл бұрын
Mind blown @The Cherno. As I said in a earlier video and will say now you are the best C++ teacher and course on KZbin. 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.
@hexi3064
@hexi3064 4 жыл бұрын
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.)
@1Naif
@1Naif 7 жыл бұрын
Also you cant initialize *const* members without using "Member initializer".
@SrogaPoziomka
@SrogaPoziomka 6 жыл бұрын
I was going to write same thing. :)
@annahakobian7371
@annahakobian7371 6 жыл бұрын
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.
@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!
@TheKingofkatz
@TheKingofkatz 5 жыл бұрын
Incredible video series that will remain relevant for years to come. Nice work man, appreciate it.
@passionfruit7617
@passionfruit7617 2 жыл бұрын
confirmed
@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!
@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 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.
@allenvicencio5156
@allenvicencio5156 7 жыл бұрын
Wanted to say thanks! Your videos are great and are a huge help to me in understanding C++.
@GreenFlame16
@GreenFlame16 4 жыл бұрын
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
@wearyadventurer404
@wearyadventurer404 4 жыл бұрын
"hey little guys my name is a chadder and welcome back to my say plus plus series" xD
@IamAtzu
@IamAtzu 26 күн бұрын
Thank you! That's a really amazing simple but clear demo
@samarthsrivastava6220
@samarthsrivastava6220 6 жыл бұрын
@TheChernoProject Man! You rock!!!. I was having trouble understanding this but you made it so simple with ur examples. Thanks!
@b_01_aditidonode43
@b_01_aditidonode43 9 ай бұрын
amazing explaination and that is amazing effect there when you said like and the like button actually glowed , woah mindblown
@h.hristov
@h.hristov 7 жыл бұрын
Thanks for the daily uploads :D
@BlackJar72
@BlackJar72 7 жыл бұрын
Yay! I finally am back online and can catch up with these awesome videos!
@mamoudgad4210
@mamoudgad4210 Жыл бұрын
I just want to thanks for this great content one of the best c++ courses on KZbin
@MiddleCross378
@MiddleCross378 5 жыл бұрын
Thank you, exactly what I was looking for.
@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.
@legendarytwister3656
@legendarytwister3656 8 ай бұрын
i didnt know that. thanks, ive watched alot of your videos you are doing great work. cheers
@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!
@dhu1090
@dhu1090 3 жыл бұрын
YOU ARE AMAZING!
@toast_on_toast1270
@toast_on_toast1270 2 жыл бұрын
Love you man, C++ for life
@gamelovers4974
@gamelovers4974 Жыл бұрын
You are the best cherno.
@asterisk4424
@asterisk4424 2 жыл бұрын
Dude thank you so much I love your videos
@ghostradiodelete
@ghostradiodelete 7 жыл бұрын
"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.
@stormwaker
@stormwaker 6 жыл бұрын
I cannot think of another KZbinr with such a high likes to dislikes ratio under his videos. Is this how perfection looks like?
@TheSunscratch
@TheSunscratch 7 жыл бұрын
Photo on the wall is awesome!
@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.
@eruston
@eruston 6 жыл бұрын
Great video, very easy to understand, bought the book: ‘effective c++ third ed.’ Great compliment to that book.
@yavuzselimcagan5233
@yavuzselimcagan5233 2 жыл бұрын
It's really good to learn that.
@meelz812
@meelz812 2 жыл бұрын
Cherno does not miss
@adrianhurtado8323
@adrianhurtado8323 3 жыл бұрын
Thank you for this!
@barellevy6030
@barellevy6030 7 жыл бұрын
Appreciate you! Great content! Thank you!
@georgei2480
@georgei2480 4 жыл бұрын
Mr. Cherno . You are my hero
@matt-g-recovers
@matt-g-recovers 4 жыл бұрын
Very cool, I like this style vs Java
@pawankumarmeena6737
@pawankumarmeena6737 6 жыл бұрын
you are my hero
@krec348
@krec348 7 жыл бұрын
YES! DAILY VIDEOS :D
@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 5 жыл бұрын
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!
@meh1672
@meh1672 7 жыл бұрын
These video's are the best! :D
@SruVekDiaries
@SruVekDiaries 6 жыл бұрын
Ur videos are awesome bro..Keep it up...u r genius
@80sremakevideo
@80sremakevideo 5 жыл бұрын
you deserve as much as subscribers as PewDiePie
@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
@smileynetsmileynet7922
@smileynetsmileynet7922 4 жыл бұрын
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...
@teosurch
@teosurch 10 ай бұрын
Thank you! Finally got the new constructor syntaxis ( a(a1) like instead of this->a = a1 );
@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.
@qandos-nour
@qandos-nour 4 жыл бұрын
thank you you are the best
@mryup6100
@mryup6100 4 жыл бұрын
This is amazing. Code changer for sure y'all!
@AdityaPrasad007
@AdityaPrasad007 5 жыл бұрын
3:17 why why!! thank you for asking that. wow... performance issues. good enough for me.
@jitendraraghuwanshi1365
@jitendraraghuwanshi1365 Ай бұрын
also if the Example class does not have a default constructor then initializing it inside constructor body does not work, it should be explicitly initialized in the initializer list.
@Nick-lx4fo
@Nick-lx4fo 4 жыл бұрын
Thank you
@hpsmash77
@hpsmash77 3 жыл бұрын
i can hear a robot talking in background lol confirmed cherno is not a human
@tessa10001
@tessa10001 5 жыл бұрын
amazing, thanks
@reguret2976
@reguret2976 5 ай бұрын
you can't initialize const and reference members without the initializer, ty for the vid very helpful :)
@leixun
@leixun 4 жыл бұрын
*My takeaways:* Why should we use member initializer lists 3:10: clean code and speed advantage
@vyomraj3389
@vyomraj3389 4 жыл бұрын
Wow thanks!
@joseponce6250
@joseponce6250 3 жыл бұрын
brillant!!
@fadyhany6818
@fadyhany6818 Жыл бұрын
in this video exactly in 00:12 you said " initialize our class member functions " i think you meant " class member ( the variables that are members in the class ) " not " member functions " , right ?
@amrtcpp6203
@amrtcpp6203 4 жыл бұрын
thanks man , you save 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.
@BatmanBottomG
@BatmanBottomG 3 жыл бұрын
caption really says, hey little guys my name is a cheddar. NOOooOoOoo
@chiyungchu9463
@chiyungchu9463 3 жыл бұрын
Why not immediate initialize them inside the class instead of inside constructor?
@NeZversSounds
@NeZversSounds 4 жыл бұрын
Another frustration explained!
@dr3mro
@dr3mro 5 жыл бұрын
we need a series of wxwidgets :)
@donovantheprogrammer2989
@donovantheprogrammer2989 5 жыл бұрын
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 жыл бұрын
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).
@sergeyklassen9696
@sergeyklassen9696 7 жыл бұрын
Great video! Did you change the audio settings? Sounds different.
@MrDivad006
@MrDivad006 6 жыл бұрын
5:55, this is so confusing. Why would it run that code before the code in the constructor?
@Netrole
@Netrole 5 жыл бұрын
It runs the code so the variables you are assigning values to in the constructor actually exist
@BernardoSOUSAstudent
@BernardoSOUSAstudent 4 жыл бұрын
That.... was totally new to 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
@waiitwhaat
@waiitwhaat 4 ай бұрын
"I don't discriminate between primitive type and class type" I'll cheers to that. (I code in Python)
@ashtonkusmaul6907
@ashtonkusmaul6907 2 жыл бұрын
what if you used like std::string& then would it still douplicate it
@l3aIIin23
@l3aIIin23 5 жыл бұрын
Thanks!
@valentinamerturi2330
@valentinamerturi2330 6 жыл бұрын
greate video!
@johnk6598
@johnk6598 3 жыл бұрын
Would default arguments be another way to accomplish this?
@我有一个朋友-i2u
@我有一个朋友-i2u 4 жыл бұрын
Today's hair is also just perfect.
@adamhendry945
@adamhendry945 Жыл бұрын
Can you please do a video on padding and alignment as well as the pIMPL idiom?
@pfomrak
@pfomrak 26 күн бұрын
You forgot to mention initializer lists usage with inheritance (calling a superclass constructor)
@jubranoo
@jubranoo 4 жыл бұрын
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 жыл бұрын
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?
@rajakandukuri8509
@rajakandukuri8509 4 жыл бұрын
this nice trick made me get rid of heap alloc.
@1tsyB1tsy
@1tsyB1tsy 5 жыл бұрын
Loving your videos but the room your recording in has a nasty resonance at 2kHz -4kHz, consider some acoustic dampening panels!
@VanBhardwaj
@VanBhardwaj 4 жыл бұрын
they are 3 years old. This won't help now :P
@AviPars
@AviPars 2 жыл бұрын
Please do a video kn std containers. Lists and algos like for each
@DaemonJax
@DaemonJax 2 жыл бұрын
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.
@zyro9922
@zyro9922 4 жыл бұрын
Too awesome.
@ohmnamo7056
@ohmnamo7056 4 жыл бұрын
wow ...gr8 explanation.....thanks a lot...
@ataladin87
@ataladin87 3 жыл бұрын
5:39 i don't understand that part. I'm not getting a value when i'm using string
@imninja4220
@imninja4220 6 жыл бұрын
in short, constructors assign the variables to a new value while member initialiser list simply initialise them
@flecko5
@flecko5 2 жыл бұрын
Good summary
@moazelsawaf2000
@moazelsawaf2000 5 жыл бұрын
Thanks a lot sir
@filippovolpe746
@filippovolpe746 4 жыл бұрын
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.
@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...
@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.
@cubedude76
@cubedude76 Жыл бұрын
Is this also how I should be initializing struct members variables?
@ilyosbeknajmiddinov6754
@ilyosbeknajmiddinov6754 2 жыл бұрын
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
@lightps5515
@lightps5515 Жыл бұрын
What is the downside of initializing a variable in the header instead of the constructor especially for the primitive data types?
@mint6276
@mint6276 3 жыл бұрын
A heads up: you can't initialize inherited values this way unless you redefine them.
@dogaruionut-beniamin1261
@dogaruionut-beniamin1261 3 жыл бұрын
Also, if a default constructor is not available you can't even avoid using the initializer list.
@wsk3184
@wsk3184 7 жыл бұрын
What if I want to initilize some member object based on some condition? E.g. class Test{ private: Object a; public: Test(int b) { if (b > 0) a = Object(b + 10); else a = Object(b - 10); } } Based on what You said Object will be created twice. Can this be avioded is this example?
@mikhailsobol3895
@mikhailsobol3895 7 жыл бұрын
In this particular case, you can use ternary operator Test(int b) : a(b > 0 ? Object(b + 10) : Object(b - 10)) {}
@Rob-nx1dz
@Rob-nx1dz 7 жыл бұрын
Test(int b) : a(b > 0 ? b + 10 : b - 10) { } should work I think
@wsk3184
@wsk3184 7 жыл бұрын
Sure, but what if the condition is more complex ? Additional else if.
@Rob-nx1dz
@Rob-nx1dz 7 жыл бұрын
for really complex conditions i think there is no way but nesting those one-line-ifs... at least I can't think of anything better
@Trogzul
@Trogzul 7 жыл бұрын
Like many other have mentioned, you can use the ternary operator. If the condition is really complex, you can use a lambda (Which he hasn't covered in depth yet), or just create a function, example: hastebin.com/omaliderat.cpp I personally would prefer just using a function rather than a lambda in most cases, but that depends on the situation.
Ternary Operators in C++ (Conditional Assignment)
8:01
The Cherno
Рет қаралды 129 М.
lvalues and rvalues in C++
14:13
The Cherno
Рет қаралды 333 М.
Cat mode and a glass of water #family #humor #fun
00:22
Kotiki_Z
Рет қаралды 42 МЛН
99.9% IMPOSSIBLE
00:24
STORROR
Рет қаралды 31 МЛН
Beat Ronaldo, Win $1,000,000
22:45
MrBeast
Рет қаралды 158 МЛН
So Cute 🥰 who is better?
00:15
dednahype
Рет қаралды 19 МЛН
Stack vs Heap Memory in C++
19:31
The Cherno
Рет қаралды 590 М.
Member Initializer Lists | C++ Tutorial
23:10
Portfolio Courses
Рет қаралды 10 М.
ITERATORS in C++
17:09
The Cherno
Рет қаралды 218 М.
Templates in C++
17:58
The Cherno
Рет қаралды 611 М.
Every single feature of C# in 10 minutes
9:50
Train To Code
Рет қаралды 173 М.
Writing My Own Database From Scratch
42:00
Tony Saro
Рет қаралды 268 М.
Fast Inverse Square Root - A Quake III Algorithm
20:08
Nemean
Рет қаралды 5 МЛН
you will never ask about pointers again after watching this video
8:03
Master Pointers in C:  10X Your C Coding!
14:12
Dave's Garage
Рет қаралды 344 М.
Cat mode and a glass of water #family #humor #fun
00:22
Kotiki_Z
Рет қаралды 42 МЛН