Member Initializer Lists in C++ (Constructor Initializer List)
Вставка
- Опубліковано 7 лют 2025
- Patreon ► / thecherno
Twitter ► / thecherno
Instagram ► / thecherno
Slack ► slack.thechern...
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
watched this earlier today and have just written my first constructor initializer list
i confess, i'm feeling pretty gangster right now
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.
*Charno
Lost it at the closed captions.
"Hello guys my name is a cheddar"
Cheddar Bob
@@nijucow i ALWAYS hear: " My name is 'Ocherno' "
I always hear it: "My name is the Cyano"
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.
Exactly, needs better documentation.
Mind blown @The Cherno. As I said in a earlier video and will say now you are the best C++ teacher and course on UA-cam. 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.
Also you cant initialize *const* members without using "Member initializer".
I was going to write same thing. :)
if I'm not mistaken reference types also must be initialized in the initializer list
What about static .?
@@venkateswarans1012 Well, those will be initialized by default I think, because you can access them without creating an object
Basically all members which should be initialized at time of declaration should be written in initializer list like const , references etc.
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.)
Holy cow. It's like a constant stream of videos!! I use some of your videos as reference for my high school classes. Cheers!
Incredible video series that will remain relevant for years to come. Nice work man, appreciate it.
confirmed
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
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.
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.
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.
Thank you! That's a really amazing simple but clear demo
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!
amazing explaination and that is amazing effect there when you said like and the like button actually glowed , woah mindblown
Don't forget Member Initializer Lists can also be used for initializing const member variables as well!
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.
i didnt know that. thanks, ive watched alot of your videos you are doing great work. cheers
Wanted to say thanks! Your videos are great and are a huge help to me in understanding C++.
I just want to thanks for this great content
one of the best c++ courses on UA-cam
"hey little guys my name is a chadder and welcome back to my say plus plus series" xD
This video should come before the virtual functions video!
Greatgreat video though, I will forever use this from now on!
@TheChernoProject Man! You rock!!!. I was having trouble understanding this but you made it so simple with ur examples. Thanks!
Thanks for the daily uploads :D
Yay! I finally am back online and can catch up with these awesome videos!
Dude thank you so much I love your videos
YOU ARE AMAZING!
Love you man, C++ for life
Thank you, exactly what I was looking for.
"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.
Photo on the wall is awesome!
You are the best cherno.
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 :)
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.
I cannot think of another UA-camr with such a high likes to dislikes ratio under his videos. Is this how perfection looks like?
Thank you! Finally got the new constructor syntaxis ( a(a1) like instead of this->a = a1 );
Mr. Cherno
. You are my hero
Cherno does not miss
Great video, very easy to understand, bought the book: ‘effective c++ third ed.’ Great compliment to that book.
It's really good to learn that.
Very cool, I like this style vs Java
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
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!
Thank you for this!
what if you used like std::string& then would it still douplicate it
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
you deserve as much as subscribers as PewDiePie
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.
i can hear a robot talking in background lol
confirmed cherno is not a human
you are my hero
Can you please do a video on padding and alignment as well as the pIMPL idiom?
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 ?
Another frustration explained!
Appreciate you!
Great content!
Thank you!
YES! DAILY VIDEOS :D
Ur videos are awesome bro..Keep it up...u r genius
Thank you
I am quite sure, that if you try this in Release mode, then you get the same result with init list and without.
brillant!!
These video's are the best! :D
Please do a video kn std containers. Lists and algos like for each
thanks man , you save me
*My takeaways:*
Why should we use member initializer lists 3:10: clean code and speed advantage
Why not immediate initialize them inside the class instead of inside constructor?
thank you
you are the best
5:39
i don't understand that part. I'm not getting a value when i'm using string
This is amazing. Code changer for sure y'all!
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...
Wow thanks!
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...
That.... was totally new to me.
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.
Look at webassembly
3:17 why why!! thank you for asking that. wow... performance issues. good enough for me.
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?
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).
you can't initialize const and reference members without the initializer, ty for the vid very helpful :)
this nice trick made me get rid of heap alloc.
"I don't discriminate between primitive type and class type"
I'll cheers to that. (I code in Python)
amazing, thanks
Great video! Did you change the audio settings? Sounds different.
I just realized his voice sounds exactly like the character Lawrence (Prince Naveed's butler) in the Disney movie, the princess & the frog.
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.
what does const std::string& GetName() means? why did we put the & sign in the return type ?
@Peterolen can we say that all what references do is to avoid unnecessary copies ?
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?
we need a series of wxwidgets :)
5:55, this is so confusing. Why would it run that code before the code in the constructor?
It runs the code so the variables you are assigning values to in the constructor actually exist
You used this in one of your previous videos (maybe the virtual functions) and I was so damn confused .
ps : I get it now
Today's hair is also just perfect.
greate video!
Is this also how I should be initializing struct members variables?
Thanks!
Would default arguments be another way to accomplish this?
wow ...gr8 explanation.....thanks a lot...
Loving your videos but the room your recording in has a nasty resonance at 2kHz -4kHz, consider some acoustic dampening panels!
they are 3 years old. This won't help now :P
Too awesome.
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) {} ) ?
What is the downside of initializing a variable in the header instead of the constructor especially for the primitive data types?
You forgot to mention initializer lists usage with inheritance (calling a superclass constructor)
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.
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 ;)
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.
Hopson wow, quick and brief. Thanks :)
@@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.
caption really says, hey little guys my name is a cheddar.
NOOooOoOoo
in short, constructors assign the variables to a new value while member initialiser list simply initialise them
Good summary
Thanks a lot sir
Thanks 😊 🙏🌹❤️
why do you pass it in by reference into the constructor?