In C++, objects can be created on the stack using direct instantiation (e.g., ClassName obj;), which provides automatic memory management where objects are destroyed when they go out of scope, or on the heap using the new keyword (e.g., ClassName* obj = new ClassName();), which requires manual memory management with delete to prevent memory leaks; stack allocation is generally preferred for its simplicity and performance unless the object needs to persist beyond its scope or exceeds stack size limitations.
How to Create and Instantiate Objects in C++
Added:hey what's up guys my name is the chato and welcome back to my C++ series I don't know what this hand stuff is today I'm gonna be talking all about how you should be creating your objects in C++ because C++ gives us a few different ways we can actually create an object now if you don't know what an object is or what a class is you definitely want to check out the video that I met on that there'll be a card on the screen or a link in the description below but basically when we've written a class and it comes time for us to actually start using the class that we've created we need to instantiate it usually unless it's like completely static but what I'm talking about that we need to instantiate our class how do we do it we basically have two choices here and the difference between the choices is where the memory comes from which memory were actually going to be creating our object in when we create an object in C++ it needs to occupy some memory even if we write a class that is completely empty no members no class members or nothing like that it has to it has to occupy at least one byte of memory but that's usually our case we have a lot of members in our classes and they need to be stored somewhere when we decide I want to start using this object I'm gonna create a bunch of variables the object has a bunch of variables we need to allocate memory somewhere in our computer so that we can actually remember what what what the variables are set to and their application is kind of added into two main sections of memory the stack and the heap now there are other sections of memory such as the area where our source code lives so by this point it's machine code so there's other sections of memory we're gonna talk about them later they don't really matter right now just think of it as the stack and the heap that's all we care about right now I am going to make an in-depth video about what the stack is and what the heat Bay is in this stack bus is behave and all that stuff if I've already made it when you're watching this video there'll be a card there if not it's coming soon so just hold on tight in C++ we get to choose where it goes whether our object gets created on the stack or on the heat and they kind of have different functional differences stack objects for example have an automatic lifespan right their lifetime is actually controlled by the scope that they declared and as soon as you as soon as that variable goes out of scope that's it that the memory is free because when that scope ends the stack pops and anything that was in that in that scope frame in that stack frame that gets that gets frayed now the heap is is different the heap is this big big big mysterious place where once you've allocated an object in that hip and you've actually created an object on the heap it's gonna sit there until you decide I no longer need it I want to free that object do whatever you like with that memory so let's take a look at what the code looks like for both of those methods of creating objects over here I've got a class called NC which just has a string now this string is just simply a sanest Raina put a little using up here just to simplify this code a little bit so that we're not writing STD string everywhere I usually do this because I don't like using namespace STD I know a lot of you ask me why I don't like using namespace STD I'm gonna make a video on that very soon so just wait for it but basically we've got a class with one member is a string and then we've got one constructor which doesn't take any parameters another constructor which does take in a string as a parameter and then we just set the name to whatever the parameter is and then finally we just have a simple getter thing the name so I'll just made like a little dummy class now let's try and create it in the main function how do we do that well the first option which is creating it on the stack is very very simple we basically type in the type of the class that we want to instantiate then we hit the spacebar and then we give it a name someone I call this entity and that's all there is to it now because we've written it like this it's actually calling the default constructor right this code might look a little bit weird to you if you're coming from a language like C sharp or Java in fact you might think this this leads to something called a null pointer exception or a null reference exception because it appears like we just haven't initialized our object but we have right as long as we have this default constructor here this is totally valid code we can now call and see don't get named and what we'll actually get is well we'll get the name we'll get unknown in this case because that's what the default constructor did so print this out to the console and see what we get there we have it unknown because what we've done here is actually different to what this code would have done in Java or C sharp and kind of will kind of get there in a minute if we wanted to specify a parameter all we need to do is just open our parentheses and give a name such as Cherno you can also do it this way we can write equals and then the type that's our constructor done right and if we hit up five to run our program we get chatter this time and everything's great so what's the deal with this when do we want to create our objects like this the answer is pretty much all the time if you can create an object like this do create an object like this that's basically the rule because this is the fastest way in C++ and the most managed way in C++ to actually instantiate objects now let's talk about why why there would be reasons where you can't do this one of the reasons is if you actually want this to live outside of the life of this function if we had another function over here and we created our entity over in that function then as soon as we reached the end as soon as we reach this this this end curly bracket this entity gets destroyed from memory because what happens is when we call function a stack frame gets credit for this function which contains all the local variables that we declare which includes primitive types but also our classes our objects and when this function ends that stack frame gets destroyed which means that all of the memory that we had on the stack all the variables we created are gone so let's write some code that would actually fail scopes don't necessarily need to be functions they could be if statements for loops or even empty scopes in which we just have curly brackets like this if I've read an interesting point uh now this is this is basically a variable which points to an entity over here I'm going to assign it to the memory address all Barents the object that we've credit on the stack right over here I'm also going to simplify this because I usually write code that looks like this I'm going to hit f9 on this line just to set a breakpoint and we'll we'll inspect this so right over here we create a new entity object grade it's got the name everything's great when I hit f10 to move down you can see that we've now set our 8.0 right so if we hover over a it is in fact pointing to this correct memory address in the name is cheddar that's great however if we hit f10 again and we advance to this line and then maybe the next line and we hover over look at that it's still pointing to that same address that the name is gone because that object was was freed it was destroyed gone this channel HD doesn't exist anymore we were aged into the stack frame it's gone that's the end of China that's the end of that tremor go on cellular that's good right so if we wanted this channel to somehow live outside the scope we couldn't allocate it on the stack we would have to resort to heap allocation the other reason why we might not want to we'll be able to allocate on the staff is because if the size of this entity is actually too large we maybe have too many entities we might not have enough room to actually allocate on the stack because the stack is usually quite small it's usually one megabyte two megabytes it kind of depends on your platform and your compiler but if you have this giant class or you want to have a thousand of these classes you might not have enough room on the stack so you might have to allocate upon the heap let's take a look at what heap allocation looked like so if we wanted to convert this current here to actually allocate on the heap what we would do is we would first of all need to change the type the type is now no longer entity the type is an entity pointer and what we assigned to entity here is new entity now the biggest difference here is actually not the pointer which a lot of people notice it's the new keyword the new keyword is K and that's gonna be video on that new keyword very soon maybe even tomorrow we'll see and when we call new and see what actually happens is we allocate memory on the heap we call the constructor and this new entity actually returns an entity pointer it returns the location on the heap where this entity has actually been allocated which is why we have to assign us to an HD pointer and this this is where you people who know Java and c-sharp this is this is what the code actually looks like in Java or C sharp you would be writing code like this so usually when you come to C++ your instinct would be probably just to change the time and suddenly smashes Java code in c-sharp code and you're right it does matter Java and c-sharp code we just have an extra option in C++ so we can allocate on the stack you can't actually do that in Java or C shop in c-sharp you can in c-sharp there's something called a struct and that's a value-based type and so that actually is kind of allocated on the stack even though you use the new keyword but in Java everything's on the heap and it's a shop all classes on the hate the struct keyword is a bit different than it isn't it's a plus plus and one of the biggest problems that I see is that everyone who comes over from a managed language like Java or C sharp just uses the new keyword everywhere in C++ and you shouldn't be doing that for two reasons and those reasons we're going to talk about in that new video because this video is going to be huge if I talk about absolutely everything but to cut it short performance allocated on the heap takes longer than allocating on the stack and also wedding allocate on the heap you have to manually free that memory that you've allocated so once we do something like this in our safe us+ code we are actually responsible for freeing that memory say plus boss is not going to suddenly decide okay you're done with this entity object it doesn't know that we're done with it we have to tell it this memory is free and the way that we do that is we call delete and then the variable name so delete entity if you use the new keyword you use the delete keyword to clean up after yourself that is how simple sauce works so in our example since we do have to actually call delete to free this object if we were to remove delete down over here maybe even after this send get we're assigning this entity on to e so we'll get rid of this apps and we don't need it since entity is already a pointer and since NC is a pointer we actually have to either dereference this first and then call get name or we can use the error operator which does that for us gonna have a video on the arrow operator certain I'm getting tired of doing this but yet more videos and if we go down over here we'll just change the late entity to be delayed a so this is what our code looks like now we create an entity on the heap we assign and C to this we're not copying any data here really what doing is whether storing the memory dress the fantasy while copying the actual HD object just the memory address and if I hit f5 will be bugged this will hit f10 you can see that it gets set correctly we have our name sugar I'll get f10 again I'll go to I'll go to the scene get I'll hop on my mouse over in you can see it still has the name Chennai right because it only gets deleted and it gets free here and those are the two ways that we can create objects in C++ and choosing between the two is a matter of is my objects really really really big or do I want to explicitly control the lifetime of my object if you answered no to both of those questions I locate on the stack right create or get on the stack it's way easier it's automated and it's faster whereas allocated on the heap requires you to manually called delete which can lead to memory leaks if you forget to call delete I mean it's a bit harder than just like forgetting a lot of people think well how often you forget to call the waiter people knew you can you can miss it sometimes I guess it's good it gets complicated as well as well as will discover you can also use something called a smart pointer we're kind of gonna get to those eventually and Lincoln that I don't even know I'm getting really tired of doing this I'm not gonna keep track of this by the way I want to come back it's not like I'm gonna come back to this video in a few months and be like oh yeah better fill in all those cards so just search my channel for those videos if they're there that they're for the north panel but with smart pointers we can actually kind of still allocate on the heap and still get that kind of size advantage but also have our objects be automatically deleted when either the pointer goes out of scope or maybe like in the case of shared pointers when there are no more references will talk about oldest memory stuff in the future I don't want to get into it right now but if we're just talking about kind of primitive C++ two ways to make objects stack and heap those are my recent spread on the stack unless you absolutely can't do you guys enjoy this video then you can hit that like button and you can support this series on patreon.com for such the chair oh you'll get episodes early basically as soon as I'm done editing the episodes get released to all the patrons which is pretty cool you can also discuss and talk about what goes into these videos and make suggestions for new videos and all that fun stuff and you also help support this series and make sure that I keep making videos next time I'm pretty sure we're gonna talk about the new keyword so that should be exciting definitely watch that video it'll be in the haha I'm done goodbye you
Up Next

Understanding Pointers in C++: A Comprehensive Guide
@javidx9
575.9K views•2018-09-29

BitTorrent Protocol Explained: Piece Selection & Peer Choking
@StevenGordonAU
481 views•2013-02-22

Understanding Pointers in C++: A Beginner's Guide to Memory Management
@TheCherno
1.2M views•2017-06-11

Enigma Machine Mechanics: WWII Encryption Explained
@JaredOwen
13.2M views•2021-12-11
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Computer Science







































