+ 6
what are constructors and how and *when* to use it?
2 Antworten
+ 3
Constructors are called when an object is created. You can use this for a lot of different things.
If you have a class called Person with a string name in it you can define a constructor takes a string as argument and set the name directly on creation.
You can now create the object like this:
Person persons("Jimmy") and it automatically sets the name variable to "Jimmy".
Here is a code of an observer pattern. When creating a battleship it automatically sets the correct mothership and also gives the mothership the command to add it to it's notification list. You don't really need to understand it in detail yet, but just to give you an additional example of a usecase:
https://code.sololearn.com/c8UbMs6vj3a9/?ref=app
+ 1
A constructor is a special method in a class that initialises an object of its type.
It is useful in many ways :
like you declare a class and you initialise only some attributes of it and some of them not. In that case, even if you didn't declare a constructor inside the class it will call default constructor and will initialise default value to it so, that some value is assigned to each and every variable.
eg. you have not initialised any value to INT variable then it will take default value i.e.0