Тёмный

How to CREATE/INSTANTIATE OBJECTS in C++ 

The Cherno
Подписаться 661 тыс.
Просмотров 243 тыс.
50% 1

Опубликовано:

 

30 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 282   
@MrPsycho2211
@MrPsycho2211 7 лет назад
Better series than Game of Thrones
@PflanzenChirurg
@PflanzenChirurg 7 лет назад
AMEN
@matiasdaneri1142
@matiasdaneri1142 7 лет назад
Not really, but it's close!
@RobYourHeart007
@RobYourHeart007 6 лет назад
You bet
@Gilpow
@Gilpow 6 лет назад
As if it was hard to achieve
@mcw0805
@mcw0805 6 лет назад
this comment made my day.
@explorerofworlds512
@explorerofworlds512 4 года назад
Cherno: "That's the end of Cherno." Me:"NOOOOOOOOOOOOOOOOO!!!!!" Cherno:"I am still here though" Me: "Oh thank GOD"
@bpm.coding
@bpm.coding 3 года назад
Imagine that's how he ended his channel
@CRBarchager
@CRBarchager 7 лет назад
For future videos, Cherno. 1:35 Stack and heap video 2:50 Why I don't like std namespace 7:40 The new keyword 10:10 Arrow operator 11:30 Smart pointer Now you can come back and put comments on your video. You're welcome :D - Love this series!
@GfastGao
@GfastGao 5 лет назад
I think we'd try harder to motivate Cherno. I've tried really a little bit effort to be kinda RU-vidr more then 3 years before. At that time, I even only have had a freelancer job, which means I had a lot more time then now, but still can not easiely keeps that on. So may be we should build a much better community around / based on this series, and do use the patreon thing to support Cherno. (I've checked out that discordapp, but really not get the point easiely)
@iyappansriram9854
@iyappansriram9854 4 года назад
he made all of EM!
@michalrabek7743
@michalrabek7743 4 года назад
@@iyappansriram9854 But he forgot to put it inside the card :-(
@prototy
@prototy 8 месяцев назад
Still not there :(
@JustDoom
@JustDoom 6 месяцев назад
@@prototy :(
@Keizor1997
@Keizor1997 5 лет назад
I've been learning C++ for more than a year now, and you've just made me have a revelation with this one. It litteraly made me stop the video, grab onto my forhead and shout "I GET IT NOW!!!" out loud. It's like I've ascended, opened my third eye, activated all my chacras and connected to the cosmose all at the same time. Thank you!
@exoticcoder5365
@exoticcoder5365 3 года назад
yup we tapped into C++ Akashic Record
@SilentShiba
@SilentShiba 2 года назад
@@exoticcoder5365 🤣🤣🤣🤣
@luigiluigi8086
@luigiluigi8086 2 года назад
Lol this was literally me I never really understood the { type* name=new type } until I finally got the difference between stack and heap. And then it just clicked. It really feels amazing when the confusions fades away and you can finally answer your questions yourself.
@greatcesari
@greatcesari Год назад
and what would be the piece of knowledge that enlightened you?
@zanagi
@zanagi 9 месяцев назад
Arent we all
@h.hristov
@h.hristov 7 лет назад
Thanks for the video man! Watching your videos has become a part of my daily routine.
@do3491
@do3491 5 лет назад
same here
@TheMR-777
@TheMR-777 4 года назад
Even after 2yrs, same here as well
@BOTHLine
@BOTHLine 7 лет назад
I love the amount of videos you put out and I also love each single one of them! Keep up the great work, I'm so hyped for the in depth videos we are more and more getting in to!
@PflanzenChirurg
@PflanzenChirurg 7 лет назад
could be more in my opinion xD i understand his hints fast and i dont Need Long to adapt them
@BOTHLine
@BOTHLine 7 лет назад
Well, I even already "knew" all of the concepts so far, however it is a really nice reminder to see everything explained in such an order again. And for most of the parts you can learn something new too. Especially when it comes down to analyzing the generated assembly code underneath all the c++ stuff. Just to show what exactly happens internally. I love to know such things, without even considering if you might need them at any point. But when it comes down to optimization it is great to know how stuff will be like in assembly code so you can alter everything at your own pleasure.
@PflanzenChirurg
@PflanzenChirurg 7 лет назад
im an old rabbit in c++ too but its a really nice refresh
@slaincow4032
@slaincow4032 7 лет назад
That's what I was about to comment XD Every week was too long ;-; WE NEED IT EVER 12 HOURSS! but actually quality > quantity of course :)
@pcpardon
@pcpardon 4 года назад
Hi Cherno, Please start a series with Data Structures and Algorithms.
@alltheway99
@alltheway99 4 года назад
Good idea
@leixun
@leixun 4 года назад
*My takeaways:* Scope could be function, if statement, for loop or even empty scope (i.e. { } ) etc 4:51
@michaelwright8576
@michaelwright8576 4 года назад
Stack: → faster and better all around, if you can create an object on the stack then do it. → shorter lifespan then when allocated on the heap Heap: → If you need to extend the lifespan of the object outside of the function where it was defined, then allocate on the heap. → Use the new keyword to allocate on the heap → Anytime we use the new keyword, we must also use the delete keyword to clear that memory space when we are finished with the object.
@WinningEmpire
@WinningEmpire 4 года назад
thanks
@jimhalpert9803
@jimhalpert9803 3 года назад
Nice
@jasoncavanaugh1556
@jasoncavanaugh1556 4 года назад
This is probably the best series I've found so far on RU-vid among all the series for learning different languages. You make it so easy, and you give just the right amount of information so that we feel like we know just enough about what's going on under the hood without also feeling bogged down by too much technical information.
@Karmdanzig
@Karmdanzig 6 лет назад
Cherno, I love your videos, anyways for completion of information, one of the main problems you may have forgot to mention about allocating on the heap with new operator, is that if an exception is thrown (and not properly caught) between the new and the delete operator, then the delete operator will never be called, thus never freeing that piece of memory from the heap. Thanks for the whole series tho, you made a wonderful job :)
@AchimVandierendonck
@AchimVandierendonck 7 лет назад
I'm gonna start a list with all the concept 'he's gonna make a video about', this series will be HUGE (keep up the good work)
@mathewmccloskey8242
@mathewmccloskey8242 7 лет назад
There must be over 50 at this point
@AchimVandierendonck
@AchimVandierendonck 7 лет назад
Mathew McCloskey probably close, yeah
@abiramn9983
@abiramn9983 7 лет назад
Hahaha I'm not the only one who's thought about this
@nimrod3141
@nimrod3141 3 года назад
you don’t even realize how much this short video helped me understand what I’ve been learning for months
@pb25193
@pb25193 5 лет назад
drinking game! take a shot whenever cherno says 'im gonna make a video about...'
@AlanDarkworld
@AlanDarkworld 2 года назад
Java/C#/Kotlin dev here. I also did my fair share of C, but never tried C++. Watching your videos now to learn a new language. The difference between "Entity()" and "new Entity()" has been an eye opener for me. It all makes so much more sense now! Nice job!
@frobeniusfg
@frobeniusfg 6 лет назад
Does Cherno exist out of scope of the video? :/
@inx1819
@inx1819 3 года назад
Yep, he's heap allocated!
@NexGIndia2020
@NexGIndia2020 6 лет назад
Seriously ur videos are the best in learning. Its more addictive than "The Breaking Bad". Also, I've to say the way of teaching is awesome. Video Quality and Audio Quality, Editing is awesome
@websurfer5283
@websurfer5283 6 лет назад
I wander when we'll be getting back to the Log project we made earlier on. 10/10 video once again here. Loving the content. C++ sensei.
@Mobin92
@Mobin92 4 года назад
What on earth is that default constructor syntax (at around 4:00)? Why is the string assigned in that weird way?
@nincompoop17
@nincompoop17 2 года назад
Dude you are so entertaining to watch. The amount of value you have added to thousands of people's lives through these videos can't be fathomed.
@psawyer871
@psawyer871 5 лет назад
I love that you always compare it with Java, this helps me understand it better! Thank you so much for all this free videos, it's gold for me!
@CarbonDesignsx
@CarbonDesignsx 7 лет назад
Will you ever get through a video where you don't say "I will cover more on this in a later video" haha. Good work though so far, loving the series!
@anthonynjoroge5780
@anthonynjoroge5780 3 года назад
Well C++ has more features than you can possibly imagine. It's an extremely complicated language.
@jaw513
@jaw513 2 года назад
I'm an experienced developer with some C experience (in the distant past). But I'm finding these videos very helpful in learning C++ - much more so than the book I was reading, A Tour of C++. Even when they cover familiar topics, I always learn something new. I especially appreciate that you occasionally break out of C++'s abstractions to discuss their lower-level implications. I also have to say, having watched some other programming videos, that I appreciate the lack of dumb jokes.
@awoidf
@awoidf 5 лет назад
"It's gonna be in the HaHa" This was pure gold.
@theshermantanker7043
@theshermantanker7043 3 года назад
8:42 May not be entirely true since heap allocation is only a language specification for Java, if you looked at HotSpot you'll notice a lot of heap and stack operations are just abstractions to register based allocation at the lowest level (Java really hates allocating to anything besides registers and if it really has no other choice, the native thread stack, for some reason)
@philiphugoofficial
@philiphugoofficial Год назад
Cherno: "If you CAN create an object like this in the simplest possible manner, then do create an object like this!" The creators of the ridiculously complex framework I heavily depend on: "I will NEVER create an object like this."
@nikowill6979
@nikowill6979 7 лет назад
You forget mention destructor when object out off scope...still great video, keep up
@noctua7771
@noctua7771 6 лет назад
Brock Lesnar lol
@gabiold
@gabiold 3 года назад
I know most of C/C++, but your videos are soooo cool, fast and up to the point yet still very clear and understandable. Can you do a video about allocators (C++17 feature)?
@zenande699
@zenande699 7 лет назад
How can I free memory that i declare on the stack using the static keyword? e.g how would I free something like: static char buff[50];
@PistonMiner
@PistonMiner 7 лет назад
That's not on the stack. That's put in the data/rodata section in memory. It gets constructed the first time the code flows through that function and gets destroyed when the program exists.
@RobYourHeart007
@RobYourHeart007 6 лет назад
So does it mean that language like Java/C# allocates everything in heap and it would then also mean that CACHE miss is something that is default in Java/C# (Because they store nothing in Stack and hence caching the item is not possible) which makes them implicitly slower than C++. P.S: C# allocates struct in Stack and not in Heap
@Beatsbasteln
@Beatsbasteln 4 года назад
dude sometimes it's like you are deliberately making your room sound worse each video :D now you even have a super glassy resonance at 1k or some shit. i normally wouldn't mind but i know you are a musician. wouldn't be too complicated to put a dynamic eq on that recording. also you could turn up the saturation of your video material a bit. you always look so pale
@jannesopanen8032
@jannesopanen8032 Месяц назад
if heap allocated objects do not have visibility restrictations then why Entity* entity = new Entity("Cherno"); inside inner curly brackets cannot be deleted with 'delete entity;' outside of those inner curly brackets ?
@RogerTannous
@RogerTannous 4 года назад
Tested the Entity pointer thingie at 6:33 as in the below, but it seems e2 still holds the name! Entity* e2; { Entity entity2("Entity2"); // created on the STACK e2 = &entity2; std::cout
@himanipku22
@himanipku22 4 года назад
Say I have a class called BMX055_Accel would the following code initialize a variable of type BMX055_Accel with the name accel? BMX055_Accel accel(i2c_bus_imu);
@casperes0912
@casperes0912 3 года назад
Alternatively: Entity* e = (Entity*) malloc(sizeof(Entity)); C style!... Though this may not call the constructor...
@IBITZEE
@IBITZEE 2 года назад
glad you mentioned to "hit the space bar"... it's one bug less to debug!!! ;-) ?sooo... a block of code { } automatically creates a stack frame?? did I already told your videos are the best??? ho... in the last 3 videos... ;-)) Ok.. I'm telling it again!!! ;-)
@parthibanthangaraj6988
@parthibanthangaraj6988 2 года назад
Hey guys, need your inputs here.. i'm replicating the same code from this video... but I get different output. your help is appreciated !! #include #include using namespace std; class Entity { private: string m_name; public: Entity(): m_name("Unknown"){} Entity(const string& name): m_name(name){} const string& GetName() const { return m_name; } }; int main() { Entity* e; { Entity ent = Entity("My name"); e = &ent; cout
@footballCartoon91
@footballCartoon91 2 года назад
finally i know how to do that class Location{} class Zone{ public: Zone(){ a[0]=new Location(4,2); b[1]=new Location(3,2); } Location** a=new Location*[20]; }
@johnsindayen8684
@johnsindayen8684 Год назад
Java stores primitive type in stack, object in heap, though its not important since there are no pointer, JVM manages memory, and finalize(). C++ has to explicitly free memory. Python stores everything in heap except C functions.
@ezioarno15
@ezioarno15 7 лет назад
Sorry if i am wrong and for my poor english .I thought we were overwriting a stackframe everytime because when you call a function this happens. -> push ebp (a general purpose register where you can save some value. the value gets saved so that it won't be overwritten) -> mov ebp, esp (copying the current stack address to that register which we moved so that we can come back to it) so now all the variables get allocated after this address, then after the function is done, this happens -> mov esp, ebp (NOTE: we saved the last address in ebp[ HERE is where the magic happens current address in esp will be overwritten with that old value we stored in ebp ]) -> pop ebp (restoring the value that was in the ebp before the function call )
@shaunmacha
@shaunmacha 4 года назад
You made me start loving c++ 🤩. Thank you so much 💕
@henryzhou7069
@henryzhou7069 4 года назад
Check out 6:25 The code :std::cout
@Ldallap
@Ldallap 2 года назад
Why is the constructor initialized like that Entity() : m_Name ..... Could someone point me to a video where it is explained? or a description?
@NIronwolf
@NIronwolf 3 месяца назад
So I'm understanding this right, you don't delete 'entity' because it went out of scope at the brace. But you can still delete 'e' because it's pointing to the right place on the heap?
@GOOD__GOD
@GOOD__GOD 7 лет назад
Where is the video for stack vs heap ???
@gooseman5578
@gooseman5578 4 года назад
isn't what Straustrup doing by RAII and wants to everybody does that INSIDE class not OUTSIDE?
@landryplacid4065
@landryplacid4065 3 года назад
:) I don't know what this hands stuff means. Really :). I was caught up in that stuff too. Until I was told about it. sounds funny what it can mean........ but then u do know :)
@vinvic1578
@vinvic1578 3 года назад
Maybe a silly question, but it not possible to have a constructor with default arguments in c++ ? If it actually is, is there any reason why Cherno didn't use that in his example?
@NuLuumo
@NuLuumo 9 месяцев назад
Is it correct to say that allocating on the stack is ~= temporary, and allocating on the heap is ~= permanent unless explicitly destroyed?
@Usammityduzntafraidofanythin
@Usammityduzntafraidofanythin 2 года назад
"Hold on tight for the stack and head video!" *uploaded 4 years ago* "OH, meesa hold on real tight!"
@Konslufius
@Konslufius 3 года назад
I'm sry but as you created the object inside a function, I was so happy because that was exectly what I was looking for and you explained why this doesn't work. But my question if you can do it at all did not get answer and I got lost on the way through the tutorial.
@Algebraiic
@Algebraiic Год назад
instead of specifying "delete entity", could you have defined a destructor that deletes "this" and that way it is implicitly done any time you dynamically allocate space for instantiation of an object?
@dan110024
@dan110024 5 месяцев назад
So the heap is like the pile of junk in the corner of the room. The stack is the things that sit on my desk. The difference is that I trash the things that sit on my desk when I'm done with them. This can't be said for the junk on the other side of the room.
@Gilpow
@Gilpow 6 лет назад
7:37 " The new keyword is *key* "
@sebaaismail1951
@sebaaismail1951 Год назад
Thank you Man, you are good tutor, as java dev, i find this vidéo very important.
@snowboyyuhui
@snowboyyuhui 4 года назад
you said stack allocated objects cannot be accessed elsewhere, but I stack allocated an object within a function, returned it and it works, they use the same memory address inside and outside the function. is this bad form?
@spinFK
@spinFK Год назад
How do I know when the stack is "full" with the next object/var?
@khonello
@khonello 3 года назад
Your tutoials are like reference for people who already understand it. For a beginner it makes no sense!!
@CWunderA
@CWunderA 3 года назад
Question, how do you know if you don't have enough stack memory?
@faizydeveloper
@faizydeveloper 4 месяца назад
if I create integer pointer using new keyword should I also have to delete it at the end of scope or when we done with it?
@jackeown
@jackeown 4 года назад
at 4:20, doesn't that create two Entities and copy one into the other technically? Just curious what the difference is.
@prototy
@prototy 8 месяцев назад
Just posting a gentle reminder 6 years later to put the cards in the video
@marisolmaciel2184
@marisolmaciel2184 3 года назад
me expecting the end of the video music :D me not getting the end of the video music D:
@this_is_mac
@this_is_mac 3 года назад
He forgot to put the outro music on. Or he was trying to make a point about forgetting to delete the allocated memory lol
@vasya88
@vasya88 2 года назад
1:30 you actualy made it :) add the card
@vasya88
@vasya88 2 года назад
oh a bunch missing, oh, 11:30 lol
@dafabi6718
@dafabi6718 2 года назад
Saving my ass once again the night before my exam. Thanks a lot, man!
@frodobaggins3974
@frodobaggins3974 3 года назад
In Python is everything on the heap or on the stack? :) Sorry, I am a troll :)
@VideoLanxer
@VideoLanxer 6 лет назад
Aw guy you're damn handsome Btw :) :)
@GenericPhantom1
@GenericPhantom1 Год назад
This is when you instantiate a class but you choose where memory is stored or smth
@tartaruskelvin1319
@tartaruskelvin1319 7 лет назад
I have found you are by far one of the best programming teachers on RU-vid. I was god awful at c++ and understood practically nothing until I started watching this series. Keep it up!
@unsalad
@unsalad 2 года назад
my favorite programming language! sea pluspus
@ash_177
@ash_177 2 года назад
I don't know what the hand stuff is, got me every time :)
@moosecouture1
@moosecouture1 Год назад
Pretty sure you have covered stack and heap memory
@abdelrahmanmohamed3784
@abdelrahmanmohamed3784 3 года назад
Im going to make a video about the stack and the heap ... that was 4 y ago lmao
@mamadshonazaramonov3010
@mamadshonazaramonov3010 Год назад
Would absolutely love to see *"more videos!"* )) 10:15
@HyperDev00
@HyperDev00 2 года назад
الفاتحة على روح الرحوم "تشرتو" الذي راح مع الميموري
@李景天
@李景天 4 года назад
Why don't they make the freaking stack bigger?
@czesawh5307
@czesawh5307 Год назад
Great you solved one headache for me, thanks
@Levelworm
@Levelworm 5 лет назад
I love this series. You don't hesitate to go a bit deep in every video, even short ones, and I love it. I think the reason is that you are speaking with all your professional knowledge in heart, while many other videos are taught by academics.
@krec348
@krec348 7 лет назад
We're getting there! This series are a authentic practical C++ book ;D
@sabinbaral4132
@sabinbaral4132 3 года назад
Cherno is better than my whole university
@linternetsansfil4152
@linternetsansfil4152 4 года назад
you didn't talk about placement new
@prateekkarn9277
@prateekkarn9277 3 года назад
'It's coming soon' tis been 3 years my friend
@AndrewEbling
@AndrewEbling 2 года назад
RU-vid needs pointers to future videos :)
@Index_Nine
@Index_Nine Год назад
"It'll be in the... Haha I'm done"😂
@jiyuu329
@jiyuu329 3 года назад
but..isn't entity out of scope when you delete it ?
@informativecontent4778
@informativecontent4778 6 лет назад
could some one explain why my teacher prefers this method of using classes than the normal one and which one's better??? #include using namespace std; class sum{ private: int no1,no2,tot; public: void getdata(); void showdata(); }; void sum::getdata(){ cout
@joaoarriagaecunha8583
@joaoarriagaecunha8583 Год назад
Hi Cherno, I have another question for you.... You showed two ways of scope instantiating objects. They are "ClassName objName(8)" and "ClassName objName = ClassName(8)". But quite often I see the following sintax: "ClassName objName = 8" Is this the same as the others?
@darikostov9583
@darikostov9583 4 года назад
how can you make global instances of a class
@serkanozturk4217
@serkanozturk4217 2 года назад
Personal Notes: - Entity e(44); or Entity e = Entity(44); - Entity e; or Entity e = Entity(); but not Entity e = Entity; - Heap allocation might be necessary since stack is usually small - Heap allocation: Entity* e = new Entity(44); - Entity* e = new Entity() or Entity* e = new Entity both are allowed unlike stack allocation. - If not needed, use stack
@scarspride4988
@scarspride4988 5 лет назад
This is amazing! You teach better than school! A quick question - What happens if you do this - Entity& GetEntity() { Entity* entity = new Entity(); return *entity; } int main() { Entity e = GetEntity(); std::cout
@mayurnerkar9682
@mayurnerkar9682 3 года назад
Why the empty class has size of 1 byte?
@FaDe587
@FaDe587 2 года назад
Soo, I'm a bit late to the party, but I do have a question: How do you handle heap de-/allocation within functions? Let's suppose you have a function that allocates memory on the heap and then returns a pointer to that object. Is there some convention to signal the user that "this function allocates memory, remember to free the result"? Is it generally considered bad to even do that? Another question I have: For my first job, we were mostly coding with ObjectPascal. It was considered a sin to not immediately follow up an instantiation with a try/finally that ensures the memory is always freed. Would you do the same in C++?
@LeftoverAtoms
@LeftoverAtoms Год назад
Being the C# chad that I am, you had me at 8:03.
@markwebcraft
@markwebcraft 2 года назад
I did the option and went from c++ to c#, and I certainly remember wondering why all of a sudden EVERYTHING had to be instantiated with new which I rarely do in c++ lol
@samdavepollard
@samdavepollard 3 года назад
Exceptionally useful video. Many Thanks for sharing your knowledge.
@matt-g-recovers
@matt-g-recovers 3 года назад
It all finally clicked when you mentioned the variable scope in the function, I remembered each call as a new stack frame and it all clicked... if I need something outside of this scope, I will require something stored on the heap... what about function returns? Coming from Java this was super Confusing until this video. Thanks Cherno
@GfastGao
@GfastGao 5 лет назад
10:11 😎. I think you pretty tell the main reason why C++ is so powerful, but still has its hard time on adoption in companys. If I say writing Javascript is like driving a normal car, then writing Java & C# is driving sport cars, ==> writing C++ code is no more about car-driving, we talk about fight-jet controlling! 🎁🚀 Another neat tutorial, Thanks Cherno, you are great, RU-vid is great, C++ is great, I love the world we created in Computers.
@nibirtalukdar3736
@nibirtalukdar3736 5 лет назад
what do you mean by instantiate?
@joaoarriagaecunha8583
@joaoarriagaecunha8583 Год назад
Hi Cherno, thanks a lot for the video. I have a question for you. Is there any fundamental diference between instantiating an object with the "new" keyword like you did and with the "static" keyword like in "static ClassName objName"? Apart from in this second you can never delete the object, is there any other fundamental diference? I imagine that static variables are also stored in the heap. Aren't they?
Далее
The NEW Keyword in C++
10:53
Просмотров 245 тыс.
Copying and Copy Constructors in C++
20:52
Просмотров 429 тыс.
Stack vs Heap Memory in C++
19:31
Просмотров 569 тыс.
Stop using std::vector wrong
23:14
Просмотров 49 тыс.
Learning C++ by making a Game... in 1 Week?!
10:14
Просмотров 483 тыс.
lvalues and rvalues in C++
14:13
Просмотров 315 тыс.
How Strings Work in C++ (and how to use them)
19:26
Просмотров 460 тыс.
Should you learn C++?? | Prime Reacts
20:29
Просмотров 367 тыс.
Precompiled Headers in C++
21:30
Просмотров 156 тыс.
Object-Oriented Programming is Bad
44:35
Просмотров 2,3 млн
31 nooby C++ habits you need to ditch
16:18
Просмотров 789 тыс.