Constructors in C++
Vložit
- čas přidán 27. 08. 2024
- Twitter ► / thecherno
Instagram ► / thecherno
Patreon ► / thecherno
Series Playlist ► • C++
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
Slack ► slack.thechern...
Stream ► / thecherno
Website ► www.thecherno.com
Facebook ► / thecherno
Cherno: "We've got so much stuff to cover"
Me: *glance at playlist* video 25 / 95. Holy shit we do.
exciting but also a little bit oooooooo, scary! :-)
Sadly in three months it hasn't changed. Cherno needs to keep making videos!
Sadly in 8 months he’s made 3 videos.
@@user-dh8oi2mk4f does it cover all c++ or I have to learn more than that? I dont mean mentality of writing code. I mean the things that c++ has
@@furki6449 It doesn't cover all of c++, but it covers enough of it for you to be proficient in the language.
When I don't understand something in class, I often search for videos like these and find sub-par, low quality videos that aren't explaining things clearly. You're doing an excellent job keeping things simple, and informative. Also the quality is awesome. Keep it up brother.
Welcome to my sip of blood series.
Captions..
Lol Captions
_it was look guys my name is the china rose and back to my sip of blood series_
Cherno's output of these videos is like an infinite while loop at this point. They just keep comin. That's what I'm talking about
@Lumioze
while(true)
{
}
UGH YOU ARE MY HERO! My professor took ~3 hours to explain basic default and parameterized constructors. And we all were just walking out of lecture confused. Thank you!
5:36 totally blew my mind
You're the kind of channel whose videos I preemtively like because I just know that I am going to receive a superb explanation of whatever I'm trying to learn. You teach as masterful as you code!
Hey man just wanted to give a big thank you for the massive amount of videos you've pushed out so fast recently! It's definitely helped me further my understanding of C++ Thank you so much!
the most underrated youtuber :( you deserve more subs
the trick Log()=delete is pretty smart
Love the pace of these videos and the pace with which they're uploaded. Excited to see what kind of subjects you have in mind once the basics have been covered. Keep it up :)
Hey Man, all your videos really help me get through school.
Just keep making them and thanks for the help.
I’m a SWE refreshing on C++ for my new job, I wasn’t even searching for something as trivial as constructors, but they way you explained it made me subscribe to you in an instant! Great job!
*You are awesome*
*With you i understand C++ a lot more better than other videos.*
*Thank you so so so so much.*
*And please, make videos about "virtual" and "pure virtual" methods.*
@cherry spoon. I'm trying, English is not my first language.
@cherry spoon. You must be one hell of a deprecated individual for criticizing someone's grammar. This is a tutorial on constructors, not English fluency.
@@1Naif what is your first language?
@@jqueryadvocate2405 His social fluency was deprecated by newer releases, clearly not backward compatible
In China, I have never come into contact with any C++series as fruitful as cherno. In China, many children learn C++in order to participate in the Informatics Olympic Competition, so that they can be admitted to a good middle school. And most organizations only handed in a small part of C++,far less than this series. Thanks to cherno's C++series, I have learned a lot that I have never learned, such as object-oriented programming, how the linker works, and so on. All in all, thanks to cherno.
Trying to expand my programming skills and found you just recently. Am already thru 23 of your videos on C++ and all I can say is wow. Your approach to teaching the language is just outstanding! What I really appreciate is how you provide practical perspective to each topic. Both in explanations and in your examples. So much rich content and delivered just as I'm asking, 'so why do we ...oh I see". Thanks for putting the immense time and effort into this series. It is truly a gift and very much appreciated.
Man, I've been devouring this séries for the last weeks. You are awesome, man. I deeply appreciate your work and how much you have leveraged my knowlrdge. One day I will be able to support you as you deserve.
your videos have been more illuminating than my four years at college for computer science programming classes. Thank you! keep up the good work
3rd video on the topic and the first one to explain what’s happening clearly. Thank you!
Slowly falling in love with C++ in spite of all the experienced programmers around me telling me it was created terribly... I don't really have much to go off of though. I've only been programming with c for the past two months or so.
2:08 Why not initialize the variables directly by doing float x = 0.0f and float y = 0.0f?
I dont think you can do that,try it and it will get an error
@@ena339 you can
My question as well
For user initialising through a constructor and directly is the same.
However ,
As seen, By using parametric constructors you can initialise and process it while the object is constructed.
You can also throw or handles exceptions that may arise which you cannot do while initialising directly.
This is soooooooo good for people with prior programming knowledge.
Other videos that just go word by word is absolute boring for me.
These vids are great ! Much appreciated.
Woah woah. I literally understood everything ʕ ꈍᴥꈍʔ
Great videos Cherno. I haven't done C++ in years, and these videos are a great refresher. I even learned some stuff along the way.
Thanks man, nailed the concept
1:26 Uninitialized isn't the same as undefined so the compiling error doesn't make sense, it should print what is in the memory regardless being initialized or not.
@5:36 the correct way to make a log class HAHA
I've tried to learn c++ couple of times but I failed every time. I've been catching up your vids so far, it's the best ever!
Funny how i've bought 2 C++ courses on Udemy during black friday then ends up watching this guy's videos for free
solid overview as always.
extremely helpful. extra efforts made (like giving various examples) are highly highly appreciated. // awesome
I was wondering why the classes weren't working, and how do they function in the first place! Thank you, honestly!
@The cherno hey bro I really love your explanations and these videos are sooo helpful. Please can you create c++ courses that are really in depth?? I mean like from the very basics to the advanced topics and please cover all the small and big details of the language. I and many others are ready to pay for such a course.
Dude you are amazing. Thank you!
What is a constructor in C++ with example?
A constructor is a special type of member function that is called automatically when an object is created. In C++, a constructor has the same name as that of the class and it does not have a return type. For example, class Wall { public: // create a constructor Wall() { // code } };
Thank you google and thank you Cherno.
Basically it is like that init method, but it gets called automatically each time you instantiate a class. Like the __init__() in Python, except you use the class name like is done in the video. Very Simple.
CHERNO LOVE YOU FELLA KEEP KILLING IT LAD
My name is China Rose and welcome to my sip of blood series... 💀💀☠️ nice captions
The delegating constructor is also a useful thing
class Entity
{
private:
float m_x, m_y;
public:
Entity() : Entity(0.f, 0.f) { }
Entity(float xPos, float yPos)
{
xPos = m_x;
yPos = m_y;
}
};
"It was look guys my name is the China rose and back to my sip of blood series".
Great explanation, good content. The only thing I wish is that u go through things slower so I dont have to replay many times
You're amazing Cherno! You're amazing!
@6:08 - in my opinion, the default constructor is one that sets some default values to the members? Log() should be a non-parameterized constructor and if we have something like Log(in, int) is a parameterized constructor
quite correct
i can prove you that math is sometimes wrong. your 6.57 minutes that you took from my life are better than my 6 hours of my professor. Nice.
Gj mate
what? instead of using the init or the constructor thing you can just replace line 6 with
float X = 0, Y = 0;
I don't get it
Peterolen so I don't need to use this and it's optional? I think it would just make the code messier because instead of adding 1 line, you add like 4.
It's better to use the constructor, it forces you to provide the needed parameters for a class so when initializing you don't forget some. The constructor is the standard for initializing classes in object oriented programming, it's better and it's what people expect.
Constructors can call functions, so it is quite convenient.
At 1:35 it is tried to print x after `Entity e`. `Entity e` should have called the default constructor and initialised the object. Thus, I assumed the print x to give out garbage value. However, it gave an error, why so?
what is the difference between Entity entity(10,20) , Entity entity = {10, 20}, and Entity entity{10, 20}?
Why use the bracket style that uses twice the space? i will never understand it
What is the difference between initialize a variable in constructor or direct in its declaration? Are there any difference in memory or performance?
You cannot initialize a member variable when it is declared, it's an error. Must be done in the constructor.
why did the print function compile when the e was not initialised?!!!
6:05
This power i didnt know i had it within me all the time
does not adding that 'f' after every assignment for the float values of X and Y make a difference if I did it without the 'f'?
if you dont put the 'f' at the end then it will assign a double instead of a float to the float variable or some weird shiz like that.
I think clang has implemented the initialization of instance variables with their default values by using the following syntax:
Entity e{};
if you do:
Entity() = delete;
Entity{} = delete;
then it won't work ofc. I guess it's just different ways of initializion a class and when you do "Entity() = delete;" you just block one of the ways. It's totally better to use first method that was shown (with private)
Every one :10
TheCherno:10.0f
please also make a detailed playlist on CMake
You forgot to mention member initialization lists (the : x(param_x) syntax), which is the more correct way to construct.
you type really fast and smooth
Doubt regarding default constructors, if i create the object as follows:
Entity e {};
if i do the above without writing a default constructor , everything gets initialized to 0. My doubt is in that case your statement "In C++ we must explicitly manually initialize " , @ 3:50 is it correct?
You can use "ctor" and double click tab
Why did the compiler have no problem with e.Print(); but couldn't handle a normal cout?
I have 2 questions after watching this awesome video:
Q1.Does 'this' or 'self' keywords exist in c++? So we can do something like other languages:
class Student
{
public:
int age;
Student(int Age)
{
this.age = Age;
}
};
Q2. why parameters in constructor cannot be the same as the property? I tried this
class Student
{
public:
int age;
Student(int age) // paramter age same as property age
{
age = age;
}
};
void main()
{
Student student(20);
std::cout
Q1, yes there is a 'this' keyword available, you can use it with '->' in your case which would look like this: student(int Age) { this->age = Age}. Q2. This also solves your next problem, youre not setting the attribute age to argument age, youre actually setting argument age to argument age. you could fix this by either calling your attribute m_age, or instead of saying age = age, this->age = age. Im certainly no expert at this, and this might be a really bad way of going about it, however it has worked for me. (this also allows your to make arrays of instances with different arguments in the constructor)
Pascal Christiaanse Thanks,dude!
turn on the subtitles before you start watching. It says he is china rose and this is "my sip of blood series".
What is the difference between using a constructor this way vs definining X =0 and Y = 0 when we declare them?
Excellent
love ur videos
constructor()=delete;
may be ignored in in c++11
since the deleted functions can be accessed.
Why not declare the variables as X = 0 and Y = 0 instead of 0.0f ?
Because he wanted those variables initialized as floats and not doubles or integers.
2:43 *cries in C*
Did you experienced what is like to program in c things that would have been better written with object oriented programming?
@@floppy-disko2378 I don't know what you mean, I meant that it's often frustrating to manualy delete the struct (for example when it contains some mallocated memory)
Thank yoU!
Int a, b, c{}; just add {} and the variables will be 0 by default if you don't initialize them and don't want to create a stupid method by default. Don't thank.:)))
Hi Cherno
I found some thing odd
it has to do with making default constructor = delete
Entity e; /* doesn't compile/run as expected /*
Entity e{} /* compiles and run */
Entity e = Entity{} /* compiles and run */
I suppose these Entity e and Entity{} uses different type of constructor, is this the case
Im new and a bit confused to how this is different from initializing the variable when you declare it like so:
float X = 0.0f, Y = 0.0f;
gave me the same results as:
float X, Y;
Entity()
{X = 0.0f, Y= 0.0f};
Can someone please clear this up for me?
I have the same doubt.
I normally do ~log instead of log = delete, but you learn something new every day I guess
Hello. Did you make a video on initialization? I cannot seem to find it in your videos.
how would i do it like in java where the parameters have the same name as the objects values, using the javas "this" keyword?
ex:
java version
class javaObj{
private int testValue;
public javaObj(int testValue){
this.testValue = testValue;
}
}
and then the c++ version?
class cPlusPlusObj{
private:
int testValue;
cPlusPlusObj(int testValue){
//what to do???
}
};
I don't understand one thing though. If default constructor set the data members to random values then why can't we print it without calling the function like you did in the beginning.
for anyone who struggles to get this working with inheritance
waiting for more complex c++ vids. good job
can someone explain why "f" is put after the number he is using as parameters (thats the only part of this confusing me)
He touched on this in the video "Variables". It's explained there
So if I want a user to name their "player" which is a class object, is it better to have a line of independent code that takes a cin input and assigns it to a member of the class object through "dot accessing" or should I have the cin input variable fed into the constructor as an argument in which the constructor assigns the argument to the "name" variable member or should I just put the cin input line of code in the constructor or should I use a getter function in the class to do some iteration of the ideas above? Seriously, it's questions like this that have been hanging me as I independently explore OOP in C++.
Love your videos but you kinda sped past what a constructor was pretty fast and talked more about initialization which was still useful. Still a great video and thank you for all you do.
we could use the whaterever in the memmory space as a random number generator...
sry for asking, but whats the difference between initialize the variables directly and having this constructor?
Your videos are helpful.
Thank you!
Best practice problems website for beginners in c++?
So, why what is left over in your memory "when you did not initialize x, and y" has exactly the same value of mine?
In other word, what does left in memory and why?
I don't know if you still need the answer but because you (and Cherno) are in the debug mode, compiler fills allocated memories with c's in hex, i.e. 0xcccc. So what you get is not random leftover data but what compiler sets uninitilized memories in debug mode to indicate you that you have used an uninitialized memory. That means you will always get the same result which is what 0xcccc means in float. But if you were in release mode, it would actually be random leftover data.
Thanks !
Starting to think i might have chosen a wrong career path, i dont understand anything its like bashing my head against a wall
You have to practice so it gets into your head. and if its something you really dont understand.. google it.
i think you forgot to explain, constructors with default parameters value. what is it useful for?
Is this correct and what it means?
class Comp
{
public:
Comp() :
itemA(0),
itemB(1),
itemC(0)
{
//some code
}
private:
int itemA, itemB, itemC;
}
Thanks, I see it is covered in Member Initializer List video
Personal Notes:
- For stack allocation: With parameter construction:Entity e(44) or Entity e = Entity(44); without parameter construction: Entity e; not Entity e(); though. Later for assigning to a different object: e = Entity(); or e = Entity(44);
How do you jump from one line to the other so quickly? 0:46
thank you
Why does the *e.Print()* compile and execute the *cout* of *X* and *Y* just fine but trying to print *e.X* in the *main* gives a compilation error? In both cases the variables are uninitialized, aren't they?
I didn't know you could force a constructor to not exist.... nice!
Please explain real-time scenario where we have to delete constructor.
For instance you have a class named math, and you only want use its static methods like mean(a, b), median(a, b). For such class you will never create an instance. In such situation you can just manually detele the constructor.
@@archsheep7772 Why wouldn't you just use namespace? That would achieve the same result.
informative and helpful! thanks
Im still not seeing why the constructor is necessary. Can't you just initialize the variables upon declaration? Like you have a class and when you say private float Y; instead say private float Y=0.0f; this is what I have been doing so is there some advantage to initializing them in the constructor instead?
@Artem Katerynych I see, thank you