What is “instantiation” in an Arduino or C++ program?

In programming and object-oriented programming in particular, “instantiation” means allocating memory to an object and preparing it for operation.

In this post, I will try to explain what instantiation is. To keep things simple and in hope that I will not also confuse you, consider this, using the code from lecture 490d of Arduino Step by Step Getting Serious (BME280 ENVIRONMENT SENSOR).

In line 81, you see this code:

Adafruit_BME280 bme;

In this line we declare (i.e. give a name) to a new object of class “bme” AND initialise it. In C++ (an object-oriented language), we can create software entities (things, constructs) that contain functionality (functions) and data (variables, constants etc), and we call these things “classes”. The class, in this example, is Adafruit_BME280, contained in a library we imported in the Arduino IDE.

To be able to use them, we give them a name, like we do with any other variable. That is what is happening in line 81.

But giving a name to an object of a class doesn’t create the object, so we can’t use it yet. It’s like giving a name to a book that you haven’t yet written. It still takes a bit of work to create the book.

This is what happens also in line 81. What this line also does is to call a special function in the Adafruit_BME280 that will also initialise it, and create a new object. The new object is given space in the Arduino’s RAM. At that point, we can start using this object, calling it by name: “bme”.

This special function I mentioned is called the “default constructor”. You can create many different constructors and name them to suit your taste, but if you don’t specify a specific constructor, then the C++ language convention is to call the default one.

It looks like this, in line 21 of the library implementation file (there are a couple more further down in the code that have parameters):

Adafruit_BME280::Adafruit_BME280()
    : _cs(-1), _mosi(-1), _miso(-1), _sck(-1)
{ }

Don’t worry about the code, but notice that the name of the function, Adafruit_BME280, is the same as the name of the class? That is what a default constructor is: a private function that has the exact same name as the name of the class.

As you can see, in a single line there’s a lot going on.

There is a very good discussion on Stack Overflow that may also help you to understand.

I hope this makes sense.

Related Articles

>