"Hello, Amigo! Now I'm going to tell you about how objects are created."
"What's so complicated about it, Uncle Rishi? You write new and the class name, indicate the correct constructor, and you're done!"
"That's true. But what happens inside the object when you do that?"
"What happens?"
"This is what happens: The object is created in several stages."
1) First, memory is allocated for all the class's member variables.
2) Then the base class is initialized.
3) Then all the variables are assigned values, if any are specified.
4) Finally, the constructor is called.
"It doesn't look very difficult: first the variables, then the constructor."
"Let's see how this works in an example with two classes:"
Code | Description |
---|---|
|
Declare two classes: Pet(pet) and Cat(cat).
In the Cat class, we see an explicit call to the base class's constructor. Here's what happens after the memory is allocated: Then the Cat class begins to be initialized. |
|
"That's a little confusing. Why is it so complicated?"
"It's actually not difficult if you know what's really going on:"
If a class does not have any constructors, one will be created automatically.
Default constructor | |
---|---|
|
|
If you don't call the base class constructor, it will be called automatically.
Call of the base class's constructor | |
---|---|
|
|
|
|
Member variables are initialized in the constructor.
Initialization of member variables | |
---|---|
|
|
What really happens | |
---|---|
|
|
"Now it's much more clear: first the base class, then variables outside the constructor, then the constructor code."
"Well done, Amigo! That's it!"
GO TO FULL VERSION