Member Initializer Lists in C++ (Constructor Initializer List)
The Cherno
·
Intermediate
·8y ago
Key Takeaways
The video discusses Member Initializer Lists in C++, a feature that allows initializing class members in the constructor, and demonstrates how to use them to improve code readability, maintainability, and performance. The video covers the syntax and best practices for using Member Initializer Lists, including initializing members in the order they are declared in the class and avoiding unnecessary object construction.
Full Transcript
hey little guys my name is a cheddar and welcome back to my say plus plus series today I'm going to be talking about constructive member initializer lists that's quite a sentence basically what it means is it so it's a way for us to initialize our class member functions in the Constructors so when we write a class and we add members to that class we usually want some way of initializing those members and that's usually done in the constructor and there are two ways we can really initialize a class member in the constructor let's take a look so I've got this entity class here which just has a name string it doesn't have any constructors yes let's add one of those may be a constructor that actually takes a name in as a parameter I'll also create one more constructor that's just going to be a default constructor and it won't take any parameters so in this case I want to assign M name with value of this name as being passed in because I want to be able to set my entity to have the name that was passed in through this parameter in this case maybe I'll do something simple and just set the player's name to unknown now this might seem fine and it's probably the way that you've been doing this in all the languages but in C++ there's actually one other way we could do this and that's why I remember initialize a list first of all let's just take a look at this card and say it running and make sure it works so I'm just going to create a new entity over here and I'm going to print the name of that entity I'll pull this one easier to demonstrate my first kind of case and then another one with a one I'll give this one a name such as shadow and we'll hit f5 you can see in this case we get online printing first in that show okay great so everything seems to work let's take a look at the second way we can initialize this instead of us just setting M name equal to the value over here we can do it via remember initialize the list which looks like this after B construct after or after you write your constructor and the parameters we can add a colon this can be on the same line as this it doesn't really matter usually I like to write it on the next line over here invented like this and then you start listing off the members that you want to initialize now in this case we've just got M name so all we have to do is type in the name of this variable and then give some kind of values in this case unknown and that kind of replaces the need to do this so this is what a member in ich lies the list is now if we had another member such as score or something like that we would just add a comma and then the value of that man but so in this case I'm initializing it to zero one thing to note really quickly is that if we had defined these variables like this in this initializer list you should be listing off all the members in order and some compilers will actually warn you if you don't write the code in order and the reason this is important is because no matter how you write your initializer list it will be initialized in the order of the actual class members I defined them so in this case the integer will be initialized first and then the string even if you write it the other way around in the initializer list where you initialize the string first and then the integer so this can lead to all sorts of kind of dependency problems if you if you break that order so just make sure that you always initialize your variables in the same order that they declare in when you declare them as members in this situation it would look like this we have our name and then we just put in the value that we want to copy from into here like this and that's how we assign this it's just you're basically replacing the equals with parentheses and moving it up into this list if we run our code you'll see we get the exact same result okay that's it that's member initializer lists really easy the big question though is why why do why should we use this is it just a Coast style thing and the answer is well yes and no norm is probably the more right answer I like writing code like this first of all because if you have a lot of if you have a lot of member variables this can get really cluttered if you start analyzing them all in here and it might be hard to see what the constructor is actually doing because maybe you've got some code later on that does other stuff but most of your constructor is filled with just initializing variables such kind of trivial and boring casts that you probably don't even want you might want to hire them which is why I like to put them in the member initializer list because just from a code style point of view I just I do I like it more it keeps my actual code in my constructor very very clean and easy to read but there is actually a functional difference different supplies to classes specifically if you write code such as this where we assign an M name to something here like unknown and you don't have it any member initializer list like so what will actually happen is this M name object will be constructed twice once with the default constructor and then again with this unknown parameter because what's happening here is actually this so you just credit two strings one of them you've just thrown away pretty much straight away right it's a waste of performance right there let's demonstrate this I'm going to make a class here called example it's going to be very very simple just one public constructor here we'll make this kind of more of a real-world example I guess I'll just print created entity over here and then I'll also create one example which actually takes in a parameter and I'll Prince rated entity with and in that X variable I'm going to scroll down here get rid of all this X stuff I'm going to add this example class as an actual class member over here I'll call it m on this Court example to adhere to my convention so this is it that's the whole class it's got two constructors one which takes no parameters and one which takes this s and what I really want to do is in my default constructor for entity my constructor which takes no parameters I just want to set example equal to an example object that actually takes in 8 right so if I come down here and I make sure I'm actually creating this let's get rid of this other example we're going to print this and we get rid of the printing it get name all I'm doing here is just creating an instance of that entity object with this default constructor if I hit f5 to run my code look at that we created two entities once with the default constructor the one that takes no parameters and once with the constructor the techs in an integer so we've actually created two entities right one was created up here it's as if we wrote this like this right I mean it created an entity here why wouldn't it create an example up here just because it's in this kind of member region doesn't mean that it's not going to run this and created and then we've also created a new example instance here and assign it to the old one so we've thrown away the old one we've just created an example class instance throwing that away and just overwritten it with a new one we've created two objects instead of just one right whereas if we were to move this into the initializer list there's two options for us here we could either write exactly the same code as we did before like this and if I hit at five you'll see of course we just we just run the constructor that we want we create one st instance or I could even just get rid of this and just passing the parameters like this and just hit a file and you can see that does exactly the same thing so there you go that's the difference right you should be using member initializer lists everywhere right there's absolutely no reason not to use them if you don't like the code style get used to them because it's not just a matter of style it's actually there's actually a functional difference you'll be literally wasting performance if you're not using them of course not in all cases in the case of primitive types like integers you it wouldn't be initialized them until you initialize them yourself by assigning it but I use it everywhere I don't discriminate between primitive classes in class types you should just be using initialized lists like this everywhere but anyway that's gonna wrap up today's episode of my C++ series look at me saying today's episode as if this is daily now I think this is the third day in a row that's why I'm doing pretty well if you guys appreciate that please hit that like button if you want to support the series you can go over to patreon the concourse at rachona I've got some pretty cool rewards set up I'm actually kind of trying a bit of a discord server so patreon rewards include that you can also join it for free though of course link in the description below like a discord thing but on patreon you get some cool rolls on that server as well as access to some of these videos early when they happen to be ready early because sometimes that just not but for those times they are available to you as soon as I basically finish editing them as well as like a we've got like a private discord / slack kind of group in which we can talk about save us bus stop external just directly as well as as well as you guys can suggest new topics and videos for me to make and that's what I usually do like this one here so I'll see you guys next time good bye [Music] [Music]
Original Description
Patreon ► https://patreon.com/thecherno
Twitter ► https://twitter.com/thecherno
Instagram ► https://instagram.com/thecherno
Slack ► https://slack.thecherno.com
Discord ► https://discord.gg/R2t97wf
Series Playlist ► https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb
Gear I use:
-----------------
BEST laptop for programming! ► http://geni.us/pakTES
My FAVOURITE keyboard for programming! ► http://geni.us/zNhB
FAVOURITE monitors for programming! ► http://geni.us/Ig6KBq
MAIN Camera ► http://geni.us/t6xyDRO
MAIN Lens ► http://geni.us/xGoDWT
Second Camera ► http://geni.us/CYUQ
Microphone ► http://geni.us/wqO6g7K
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from The Cherno · The Cherno · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
3D Game Programming - Episode 1 - Window
The Cherno
3D Game Programming - Episode 2 - Game Loop
The Cherno
3D Game Programming - Episode 3 - Arrays
The Cherno
3D Game Programming - Episode 4 - Drawing Pixels!
The Cherno
3D Game Programming - Episode 4.5 - How Rendering Works
The Cherno
3D Game Programming - Episode 5 - Playing with Pixels!
The Cherno
3D Game Programming - Episode 6 - Performance Boosting
The Cherno
3D Game Programming - Episode 7 - FPS Counter
The Cherno
3D Game Programming - Episode 8 - Alpha Support and More
The Cherno
3D Game Programming - Episode 9 - Beginning 3D
The Cherno
3D Game Programming - Episode 10 - Floors and Animation
The Cherno
3D Game Programming - Episode 11 - Rotation
The Cherno
3D Game Programming - Episode 12 - User Input
The Cherno
3D Game Programming - Episode 13 - Render Distance Limiter!
The Cherno
3D Game Programming - Episode 14 - Basic Mouse Movement
The Cherno
3D Game Programming - Episode 15 - Textures + More!
The Cherno
3D Game Programming - Episode 16 - Walking, Crouching, Sprinting + More
The Cherno
3D Game Programming - Episode 16.5 - Exporting Runnable Jars
The Cherno
3D Game Programming - Episode 17 - Small Adjustments + Birthday!
The Cherno
3D Game Programming - Episode 17.5 - Creating an Applet
The Cherno
3D Game Programming - Episode 18 - The Beginning of Walls
The Cherno
3D Game Programming - Episode 18.1 - A Few More Things
The Cherno
Episode 18.5 - Creating an EXE File in Java
The Cherno
3D Game Programming - Episode 19 - Rendering Walls
The Cherno
3D Game Programming - Episode 20 - Continuing Walls, Fixing Bugs, and Managing Crashes
The Cherno
3D Game Programming - Episode 21 - Texturing Walls, Fixing Clipping, and Fixing the Mouse
The Cherno
3D Game Programming - Episode 22 - Random Level Generator + Properly Fixing Clipping
The Cherno
3D Game Programming - Episode 23 - Graphical User Interface (GUI) Launcher
The Cherno
3D Game Programming - Episode 24 - Making Our Launcher Work
The Cherno
3D Game Programming - Episode 25 - Writing and Reading Files
The Cherno
3D Game Programming - Episode 26 - Custom Resolutions
The Cherno
3D Game Programming - Episode 27 - Decorating the Launcher
The Cherno
3D Game Programming - Episode 28 - Continuing our Custom Launcher!
The Cherno
3D Game Programming - Episode 29 - Launching The Game
The Cherno
3D Game Programming - Episode 30 - Colour Processing In-Depth
The Cherno
3D Game Programming - Episode 31 - Sprites!
The Cherno
3D Game Programming - Episode 32 - Sprite Mapping
The Cherno
3D Game Programming - Episode 33 - High Resolution Rendering
The Cherno
3D Game Programming - Episode 34 - Entities
The Cherno
Genesis - My Game for Ludum Dare 24
The Cherno
Vlog + Ludum Dare Results
The Cherno
Game Programming - Episode 1 - Resolution
The Cherno
Game Programming - Episode 2 - Threads
The Cherno
Game Programming - Episode 3 - Game Loop
The Cherno
Game Programming - Episode 4 - Window
The Cherno
Episode 5 - Buffer Strategy
The Cherno
Game Programming - Episode 6 - Graphics Initialized
The Cherno
Game Programming - Episode 7 - Buffered Image and Rasters
The Cherno
Game Programming - Episode 8 - The Screen Class
The Cherno
Game Programming - Episode 9 - Rendering Pixels
The Cherno
Game Programming - Episode 10 - Clearing the Screen
The Cherno
Game Programming - Episode 11 - "Out of Bounds, Baby!"
The Cherno
Game Programming - Episode 12 - Negative Bounds
The Cherno
Game Programming - Episode 13 - Timer
The Cherno
Game Programming - Episode 14 - FPS Counter
The Cherno
Episode 15 - Tiles
The Cherno
Game Programming - Episode 16 - The Map
The Cherno
The Walls 2 - Minecraft PvP Survival Map
The Cherno
Game Programming - Episode 17 - Key Input
The Cherno
Game Programming - Episode 18 - Controlling The Map
The Cherno
🎓
Tutor Explanation
DeepCamp AI