Casting in C++

The Cherno · Intermediate ·🛡️ AI Safety & Ethics ·8y ago
Skills: API Design60%

Key Takeaways

Explains casting in C++ for beginners and intermediate learners

Full Transcript

hey what look guys my name is a China welcome back to my C++ series so today we're gonna be talking all about costing in C++ we really haven't talked about this often although we have in fact used costing and will talk more about kind of say style costing as well as save us lost out costing and this this video one color absolutely everything we'll get into this as a series kind of goes on and I think that this topic is one of those things that you just have to practice with and kind of learn through experience rather than me just telling you this is how it works because if you just take in the theory with no practice for this specific topic it's not really gonna help you that much so just keep that in mind okay cool so first of all what is casting well what I'm talking about casting I'm specifically talking about typecasting or any kind of conversions that we have to do within the type system that we have available to us in C++ C++ being a strongly typed language basically just means that there is a type system and types enforce if I make something as an integer I can't suddenly just start treating it as if it was a double or a flirt or something like that or vice versa I have to kind of stick to my type unless there's an easy implicit conversion which means that this simple swaps knows how to convert between the two types with no data loss and basically what's labeled as an implicit conversion as well or there's an explicit conversion which is where I'm actually telling simple as hey you need to convert this type into this type now we have covered kind of casting and type conversions to an extent when we talked about type punting so if you haven't seen that video definitely check that out but in this video we're gonna kind of formally cover what casting actually means and see how we can use it so the way that we perform type conversions is visibly explicit type conversions is one of two ways really or at least I see it as one of two ways there's the kind of C style costs and then we also have a C++ style costs now if we just take a look at a quick example I just say I've gotten the integer like this I'll call it a and I'll set it equal to 5 and I want to I want to treat it as a double now in this scenario if I make a double called value and set it equal to a you can see that that we don't need to explicitly specify hey I want you a into a double because that's that's a that's kind of a conversion that it deems as implicit it's easy to do there's no data loss anything like that now if I had something the other way around where I had maybe double value equals like five point three five point two five or something like that and I wanted to convert it into a integer that would also be deemed as an implicit conversion because it's not something that we necessarily have to specify hey I'm converting this type into this type now if we did want to be explicit for example what we can actually do is just cast this double into into an integer by doing something like this right now of course in this case it implicitly is able to do that but for the sake of this let's and since we are talking about cost and let's pretend it wasn't so we have an implicit we have an explicit conversion here because we're saying I want this value to be competitive to an integer now why we need this is kind of it's not really perhaps a better example might be like if we wanted to maybe have another double here called a and we wanted to add you know five point three to this value now if we just kind of get rid of this and print what a actually is then what you might see it's obviously what you might expect with kind of adding five point two five to five point three now if I cost this value into an integer then that's going to converted into an integer which means it's going to truncate at the point two five and I'll end up just being five plus five point three which instead of giving us ten point five five would give us the value ten point three submit in this case is actually changing it and this actual technique that we've used is called a safe style cost because we basically specified the type that were causing to in parentheses like this and then the variable that we're actually costing optionally we can of course surrounded in parentheses like this which is particularly useful if maybe we wanted to cost that entire thing into an int once it had actually evaluated in fact if we do this will still get 10 as the value because value is gonna be five point two five plus five point three which gives us ten point five five and then it would get truncated into an ant now the C++ way of doing this would be by using as a both starcast and it'll be four days who would use something called a static cast and to do that basically this would look like the following so let me just get back to where we were before which is just this and then it's been this would just be a static cost what we're passing into which is it needs and then the value and then we'd add 5.3 and that would be our value now C++ tile costs we have a number of them one of them is called static cost we have something else called reinterpret cost we have something called dynamic cost and we have something something called const cost there's a kind of the four main costs now what you have to realize is that they do not do anything that C style casts cannot do what I mean by that is that sure they might do additional things but the actual conversion the result of what you get is a successful type conversion c-style cast can achieve all of that so this isn't really adding new functionality what it is adding is kind of like syntax sugar to your code now of course dynamic cast which we'll talk about specifically in another video I'll show you an example of it working here but we'll talk more in depth about what it actually does and how it works in another video that for example will actually perform a check and may return null if the conversion wasn't successful so it does do extra things which also means that it actually kind of slows you down but for the for the most part all of these hippos boss style casts don't do anything really extra they just kind of are a way to put into English words static cast for example that it's a static cast and they also do some other compile time checks in the case of static cast to see if that conversions actually at all ever possible and reinterpret cast as well is kind of putting into words the whole type Pawnee thing that we talked about it's just a way to put it into words like reinterpret cast I'm reinterpreting this memory as something else Const cast I'm removing cost I'm adding Const the benefit to having all these costs apart from those kind of compile time checks that you might receive is you can now search for them in your code base all right if I want to see where I wear my casting is maybe I having performance shoes and I want to not dynamic cast something I can search for dynamic cast I can search for static cast if you just have a cast like sa self.cards like int or whatever like we did with that previous example how you're going to search for that you can't really search for it's not something that you can of course you could use like a regex or something like that and actually just I don't know it just it wouldn't actually be practical to do that whereas here we've got actual English words that are very easy to search for so it just helps us both as a programmer reading our code and writing our code but also it helps us to reduce kind of errors that we might accidentally make if we try and cast certain things that are incompatible good example is we've got a few classes here banks derived in another class if I just try and cost this value which is clearly an int into like I don't know another class that's going to result in an error because well it came in this case it's going to be because of a constructor but if I add like a pointer or something like that now to this case you can see it's an invalid type conversion so what simple class has done is the compiler has looked at that and been like that's never gonna work right and even if we do take the memory address of it right which of course gives us an inner pointer and we try and type on it that's not gonna work it's invalid type conversion now for type owning as I just explained we would need to use reinterpret cast and if we do you can see we don't get any errors who've now reinterpreted the data that is at that value pointer into being a pointer to another class instance but the point is with with things like this it adds actual compile time checking because it knows that we can't do certain conversions whereas this wouldn't be the case of course if we just used a normal say star cast it were just kind of default to doing what a range Shepherd cast would do and I'm saying a lot of words and it might be a little bit hard to follow but again the best way to to actually learn this stuff is just a practice it try and build yourself an example of using static cast or interpret cast a Const cast a dynamic cast I'll show you a dynamic car cast example any minute but just trying to get yourself and then that's the best way to kind of work out how it actually works and when you can use each one so if we take a look at dynamic cast what dynamic class will actually do is suppose that we had maybe we made a derived class instance right so I said derived derived equals new derived and then somewhere along the line I decided to actually cast that into a base right so a base base equals derived now what I want to do later is figure out ok hey I have a base pointer is it actually a derived instance or is it in another classes since we can say they both extend base now if I try and use it what I can do with dynamic cast is actually kind of not only asked that question but attempt that conversion and do something if it fails so we know for a fact based on this code that base is actually an instance of the derived class but let's pretend that we didn't know that and we'll just say another class AC equals dynamic cast another class and then AC right and one pointer and of course ok now what's gonna happen here is if we had just used a static cast which by the way we can see we can do in this case it does the same thing as a safe star cast or if we use this a star cast it would just work like isn't it would just give us that value and of course things might go wrong later on because you know AC is not in fact another class it's actually a derived instance we've just basically type ones it but with dynamic cast what it's actually going to do is it's going to see if that is actually the case and of course over here I need to make sure I pass in base and not AC let's hit that five and see what happens so you can see once I actually do that if I hit f10 AC is equal to null because it is in fact not bad and of course you could then check it you could say if not AC or if IC equals null then maybe we know that it's not that class or a way to check for if it is that class is just to say if AC that means that the type of conversion was successful and we now know bass is in fact an instance and instance of derived right sorry an instance of another class and of course if I do change this around so it works by setting it equal to derived hit at five and then you can see if I hit up ten here it does in fact you also valid pointer because that conversion was successful so dynamic cast is a great way to see if it's actually worked now this does tie in very closely to the runtime type information RT TI and it requires requires a whole bunch of things which we'll talk about in a specific video about dynamic casting but just so you know these casting operators are kind of available to you as a way to simplify casting and to maybe make it more solid in the sense that it will do compile time checking dynamic cast will do runtime checking and you'll get all that kind of hopefully more solid code base by using casting operators like that me personally I tend to use C style casts most of the time but I do encourage if you're working on a brand new project that you're starting from scratch or if you have a very small project you should use sea salt say sorry C++ start casting like static cast dynamic re interpret cast all of that kind of stuff because those those casts do make your code more solid and are better for everyone involved really and cons car didn't really touch on but that's just literally you use it to add or remove Const to something easy you can add constantly anyway but it's mostly for removing Const and again it's good to just have that in your code base because now you can search for all the naughty times you've decided to remove Const and maybe fix that or just come up with something else as well so that's really useful and then the other thing was reinterpret cost if you look at that type hunting video that I've linked at the beginning of this video everything I did there you can basically use very Tober cost so that kind of that's what reinterpret cast is used for it's when I don't actually want to convert anything I just want to take that kind of pointer and interpret it something else I want to interpret existing memory as another type that's what our interpret caste is useful anyway I hope you guys enjoyed this video if you didn't hear that like button you can help support this series by going to patreon accomplice after the turn okay showed out to everyone who supports this series because it would not be here without you guys and it certainly wouldn't be wouldn't be an ongoing thing that I keep keep doing so yeah thank you because I love making videos for you guys I will see you next time good bye [Music]

Original Description

Patreon ► https://patreon.com/thecherno Twitter ► https://twitter.com/thecherno Instagram ► https://instagram.com/thecherno Discord ► https://thecherno.com/discord Series Playlist ► https://thecherno.com/cpp Thank you to the following Patreon supporters: - Dominic Pace - Kevin Gregory Agwaze - Sébastien Bervoets - Tobias Humig - Peter Siegmund - Kerem Demirer 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 3D Game Programming - Episode 1 - Window
3D Game Programming - Episode 1 - Window
The Cherno
2 3D Game Programming - Episode 2 - Game Loop
3D Game Programming - Episode 2 - Game Loop
The Cherno
3 3D Game Programming - Episode 3 - Arrays
3D Game Programming - Episode 3 - Arrays
The Cherno
4 3D Game Programming - Episode 4 - Drawing Pixels!
3D Game Programming - Episode 4 - Drawing Pixels!
The Cherno
5 3D Game Programming - Episode 4.5 - How Rendering Works
3D Game Programming - Episode 4.5 - How Rendering Works
The Cherno
6 3D Game Programming - Episode 5 - Playing with Pixels!
3D Game Programming - Episode 5 - Playing with Pixels!
The Cherno
7 3D Game Programming - Episode 6 - Performance Boosting
3D Game Programming - Episode 6 - Performance Boosting
The Cherno
8 3D Game Programming - Episode 7 - FPS Counter
3D Game Programming - Episode 7 - FPS Counter
The Cherno
9 3D Game Programming - Episode 8 - Alpha Support and More
3D Game Programming - Episode 8 - Alpha Support and More
The Cherno
10 3D Game Programming - Episode 9 - Beginning 3D
3D Game Programming - Episode 9 - Beginning 3D
The Cherno
11 3D Game Programming - Episode 10 - Floors and Animation
3D Game Programming - Episode 10 - Floors and Animation
The Cherno
12 3D Game Programming - Episode 11 - Rotation
3D Game Programming - Episode 11 - Rotation
The Cherno
13 3D Game Programming - Episode 12 - User Input
3D Game Programming - Episode 12 - User Input
The Cherno
14 3D Game Programming - Episode 13 - Render Distance Limiter!
3D Game Programming - Episode 13 - Render Distance Limiter!
The Cherno
15 3D Game Programming - Episode 14 - Basic Mouse Movement
3D Game Programming - Episode 14 - Basic Mouse Movement
The Cherno
16 3D Game Programming - Episode 15 - Textures + More!
3D Game Programming - Episode 15 - Textures + More!
The Cherno
17 3D Game Programming - Episode 16 - Walking, Crouching, Sprinting + More
3D Game Programming - Episode 16 - Walking, Crouching, Sprinting + More
The Cherno
18 3D Game Programming - Episode 16.5 - Exporting Runnable Jars
3D Game Programming - Episode 16.5 - Exporting Runnable Jars
The Cherno
19 3D Game Programming - Episode 17 - Small Adjustments + Birthday!
3D Game Programming - Episode 17 - Small Adjustments + Birthday!
The Cherno
20 3D Game Programming - Episode 17.5 - Creating an Applet
3D Game Programming - Episode 17.5 - Creating an Applet
The Cherno
21 3D Game Programming - Episode 18 - The Beginning of Walls
3D Game Programming - Episode 18 - The Beginning of Walls
The Cherno
22 3D Game Programming - Episode 18.1 - A Few More Things
3D Game Programming - Episode 18.1 - A Few More Things
The Cherno
23 Episode 18.5 - Creating an EXE File in Java
Episode 18.5 - Creating an EXE File in Java
The Cherno
24 3D Game Programming - Episode 19 - Rendering Walls
3D Game Programming - Episode 19 - Rendering Walls
The Cherno
25 3D Game Programming - Episode 20 - Continuing Walls, Fixing Bugs, and Managing Crashes
3D Game Programming - Episode 20 - Continuing Walls, Fixing Bugs, and Managing Crashes
The Cherno
26 3D Game Programming - Episode 21 - Texturing Walls, Fixing Clipping, and Fixing the Mouse
3D Game Programming - Episode 21 - Texturing Walls, Fixing Clipping, and Fixing the Mouse
The Cherno
27 3D Game Programming - Episode 22 - Random Level Generator + Properly Fixing Clipping
3D Game Programming - Episode 22 - Random Level Generator + Properly Fixing Clipping
The Cherno
28 3D Game Programming - Episode 23 - Graphical User Interface (GUI) Launcher
3D Game Programming - Episode 23 - Graphical User Interface (GUI) Launcher
The Cherno
29 3D Game Programming - Episode 24 - Making Our Launcher Work
3D Game Programming - Episode 24 - Making Our Launcher Work
The Cherno
30 3D Game Programming - Episode 25 - Writing and Reading Files
3D Game Programming - Episode 25 - Writing and Reading Files
The Cherno
31 3D Game Programming - Episode 26 - Custom Resolutions
3D Game Programming - Episode 26 - Custom Resolutions
The Cherno
32 3D Game Programming - Episode 27 - Decorating the Launcher
3D Game Programming - Episode 27 - Decorating the Launcher
The Cherno
33 3D Game Programming - Episode 28 - Continuing our Custom Launcher!
3D Game Programming - Episode 28 - Continuing our Custom Launcher!
The Cherno
34 3D Game Programming - Episode 29 - Launching The Game
3D Game Programming - Episode 29 - Launching The Game
The Cherno
35 3D Game Programming - Episode 30 - Colour Processing In-Depth
3D Game Programming - Episode 30 - Colour Processing In-Depth
The Cherno
36 3D Game Programming - Episode 31 - Sprites!
3D Game Programming - Episode 31 - Sprites!
The Cherno
37 3D Game Programming - Episode 32 - Sprite Mapping
3D Game Programming - Episode 32 - Sprite Mapping
The Cherno
38 3D Game Programming - Episode 33 - High Resolution Rendering
3D Game Programming - Episode 33 - High Resolution Rendering
The Cherno
39 3D Game Programming - Episode 34 - Entities
3D Game Programming - Episode 34 - Entities
The Cherno
40 Genesis - My Game for Ludum Dare 24
Genesis - My Game for Ludum Dare 24
The Cherno
41 Vlog + Ludum Dare Results
Vlog + Ludum Dare Results
The Cherno
42 Game Programming - Episode 1 - Resolution
Game Programming - Episode 1 - Resolution
The Cherno
43 Game Programming - Episode 2 - Threads
Game Programming - Episode 2 - Threads
The Cherno
44 Game Programming - Episode 3 - Game Loop
Game Programming - Episode 3 - Game Loop
The Cherno
45 Game Programming - Episode 4 - Window
Game Programming - Episode 4 - Window
The Cherno
46 Episode 5 - Buffer Strategy
Episode 5 - Buffer Strategy
The Cherno
47 Game Programming - Episode 6 - Graphics Initialized
Game Programming - Episode 6 - Graphics Initialized
The Cherno
48 Game Programming - Episode 7 - Buffered Image and Rasters
Game Programming - Episode 7 - Buffered Image and Rasters
The Cherno
49 Game Programming - Episode 8 - The Screen Class
Game Programming - Episode 8 - The Screen Class
The Cherno
50 Game Programming - Episode 9 - Rendering Pixels
Game Programming - Episode 9 - Rendering Pixels
The Cherno
51 Game Programming - Episode 10 - Clearing the Screen
Game Programming - Episode 10 - Clearing the Screen
The Cherno
52 Game Programming - Episode 11 - "Out of Bounds, Baby!"
Game Programming - Episode 11 - "Out of Bounds, Baby!"
The Cherno
53 Game Programming - Episode 12 - Negative Bounds
Game Programming - Episode 12 - Negative Bounds
The Cherno
54 Game Programming - Episode 13 - Timer
Game Programming - Episode 13 - Timer
The Cherno
55 Game Programming - Episode 14 - FPS Counter
Game Programming - Episode 14 - FPS Counter
The Cherno
56 Episode 15 - Tiles
Episode 15 - Tiles
The Cherno
57 Game Programming - Episode 16 - The Map
Game Programming - Episode 16 - The Map
The Cherno
58 The Walls 2 - Minecraft PvP Survival Map
The Walls 2 - Minecraft PvP Survival Map
The Cherno
59 Game Programming - Episode 17 - Key Input
Game Programming - Episode 17 - Key Input
The Cherno
60 Game Programming - Episode 18 - Controlling The Map
Game Programming - Episode 18 - Controlling The Map
The Cherno

Related Reads

📰
I Spent a Week Trying to Break an AI. The Hard Part Wasn’t Breaking It.
Learn how to build a prompt injection attack on an AI model and understand the challenges of measuring success in AI security testing
Medium · Machine Learning
📰
Everyone Is Chasing AI Benchmarks, Almost Nobody Is Measuring Truth
The AI community is overly focused on benchmarks, neglecting the importance of measuring truth and real-world impact, which is crucial for building practical AI solutions.
Hackernoon
📰
Politeness Is Not a Security Model — Hooks & MCP in Claude Code, Deep Dive Part 5
Learn how to secure your AI models using deterministic guardrails and a universal adapter, connecting them to tools like Figma and GitHub
Medium · Programming
📰
Kan AI blive bevidst? Tre eksperter mødtes – og blev ikke enige
Experts discuss whether AI can become conscious, but fail to reach a consensus, highlighting the complexity of the issue
Dev.to AI
Up next
Anthropic warns About This AI could escape control!
PlivoAI
Watch →