021 - C++ Constructors

We continue to learn the object-oriented programming of C++, and this issue mainly talks about the constructor .

What is a constructor?

A constructor is basically a special type of method that is run every time an object is instantiated.

Let's go straight to an example.

example time

We're going to dig into this by creating an Entity class.

iS68h8.png

This class has two member variables, float X, Y, used to describe the position of Entity. Then create an Entity instance. Give it a Print function so it can output its position to the console.

Running this code turns out to be perfectly fine without any issues.

You should notice, however, that the output looks like random values.

This is because when we instantiate Entity to allocate memory for it, we don't actually initialize that memory space, which means we actually output the original value in that memory space.

We can also explain the current situation from another angle.

Since X and Y are public, we can print X manually in the main function.

iS6NZZ.png

Debugging the code, we get an error that the local variable is not initialized. In other words, we're trying to use uninitialized memory, which the compiler doesn't allow.

Although this Print function can be compiled, what it shows is not what we expected. Since it prints X and Y directly, but they are both set to seemingly random values, this one is different.

It looks like the next task is to initialize the memory, we need to set it to 0. - We expect that the value of this position will default to 0 if a value is not specified.

I need a way that when constructing an instance of Entity, we can set X and Y to 0 unless they have been assigned other values.

One of the ways to solve the problem is to directly create an initialization method.

We can create the Init method.

iS6rHF.png

It is a function of type void, and you can see that it is only used to set the value of X and Y to 0.

Now all we can do is call this Init method when the Entity object instance is created.

Debug and run the program, you can see that X and Y are set to 0, it seems that we have completed our requirements.

However, if we do this, we will write quite a lot of extra code. Whenever you want to create an object in the code, we need to call the Init function, so when the code becomes more and more, it will become more and more troublesome to write.

It would be nice if we had a way to run this initialization code directly when the object is constructed. So, there is a constructor.

Constructor

A constructor is a special type of method, a method that is called automatically every time you construct an object.

We define it like any other method. Specifically, however, it has no return type , and its name must be the same as the class name .

iS6RTQ.png

When writing the constructor of Entity, first enter the class name Entity.

You can choose to give a parameter, which we will talk about in a moment, and the position of the parameter is empty first.

It can then be given a function body.

In this case, let X equal 0 and Y equal 0 as before. Delete the Init method, it is no longer needed now.

Run the code, and you will find that it has the same effect as the previous Init method. - The Init method is replaced by a constructor.

The reality is that if you don't specify a constructor, there is still a constructor. It's just that it's a thing called the default constructor, which is already prepared for you by default, but the default constructor doesn't actually do anything, which is the same as the body of the constructor function we defined is completely empty Effect.

In languages ​​like Java, primitive data types such as int and float are automatically initialized to zero. But this is not the case with C++, you have to manually initialize all primitive types, otherwise they will be set to their original in-memory value.

So initialization is very important.

In future series, I'll talk more about initialization and the different strategies and approaches to properly initialize memory.

Next let's look at constructors with parameters.

iS6mkE.png

Yes, in fact, you can write many constructors, provided they have different parameters. This is actually the same operation as I wrote some methods with the same name before. This process is called function overloading. It can be said that they are different function versions with the same function name but different parameters .

Here I add x and y as parameters, and then assign the values ​​of x and y to X and Y in the body of the function.

I now have the option to use parameters to construct the Entity object.

iS6pBC.pngAfter running the program, you can see 10 and 5 appear in the console, which is great.

The constructor is about the same.

There are a few more that I need to remind you of.

The constructor won't run without instantiating the object, so if you only use a static method of a class, it won't run. We haven't discussed the allocation of heap memory, which will be discussed later in the series.

The constructor is also called when the new keyword is used and an object instance is created.

delete constructor

There are also ways to delete constructors.

for example.

iS6B9P.png

We have a Log class that only has static log methods, I just want people to use the Log class like this, without creating an instance and calling the Write method.

There are two different workarounds.

We can hide the constructor by making it private.

iS6gAX.png

You can see that line 40 gets an error because I don't have access to the constructor, which is obviously allowed to construct objects by not doing so.

C++ provides us with a default constructor. However, I can tell the compiler: I don't want that constructor anymore.

We can do this.

iS6xrt.png

You can see that there is an error in the instantiation, because the default constructor does not exist, it has been deleted.

final words

There are also some special types of constructors, such as copy constructors, move constructors, etc. Each of them will have its own issue because they are all complex.

This is the basic use of the constructor, just remember one sentence: it is a special method that runs when you create an instance of a class, and its main purpose is to initialize the class. When you create a new object instance, the constructor ensures that you initialize all the memory and do all the setup you need to do.

That's it for this issue. If you have any ideas, you can put them in the comment area, see you next time.

Guess you like

Origin blog.csdn.net/qq_40186237/article/details/130337551