Class Constructor

3 minutes
Share the link to this page
Copied
  Completed
Learn about how class constructors can be used to set up objects upon their creation.

Transcript

Hello, welcome to the 20th tutorial of the swift programming theories. And we're gonna be looking at class constructors today, class constructors run when an object is created of that class. In the previous tutorial, we looked at classes. And even though we didn't implement a constructor, ourselves, there was a default constructor. So just bear that in mind. But you can also create your own constructor.

And this allows the flow variable set to take place. By default. Each class has a constructor, like I mentioned, but you can specify your own. We can have we can even have multiple instructors that occur depending on how you create the objects, because you can also pass in parameters constructed will just look very much like a regular function. So let's just open up our project. And what we're going to do this simply create a class similar to the last tutorial and of course Recall crypton variables be the Port 100 over a question cram, you make equal to 100 in it.

And in it basically stands for initialized and this is the constructor. And by default it's this one is code if you don't provide any parameters when you instantiate an object, we're going to create an awkward in it. And in here we're just going to have three variables be tempted to be an end. This is gonna be another rant and in here within this speed equals speed temp. Drunk equals cram 10 to create function code Phone damage car damage came in here with a nice month he was done man. In the vehicles car, when we instantiate it, we're going to put the temp code London the value of speed is going to be 500.

We're going to put cram 10 countdown that's going to be 987. And that's how you construct a class I mean an object of a class. You can either have nothing inside it which we did in the previous tutorial, and this would call this function or your wish they might find the campus stuff in there as well or you can put stuff in there and it will call this one What we're gonna do is just do 29 BMW drove the beam the beta damage car 24 inch line and inside we're going to put B in the B dot stream. So if we run this now we got 987 which is what we specified when we constructed it and 967 which is what would happen when you take 20 away from it. So that's it for this tutorial in the next tutorial when I look at enumeration The only question feel free to message us at support at sonar system code ek the my will be in the description.

You can comment on this video or directly message us via YouTube or the requirement for source code will also be in the description. And as usual, thanks for watching and have a nice day.

Sign Up

Share

Share with friends, get 20% off
Invite your friends to LearnDesk learning marketplace. For each purchase they make, you get 20% off (upto $10) on your next purchase.