When Class Instantiation is Required

I can use the Serial class function, as in Serial.begin(9600), without including the header file.

I can use the Wire class function, as in Wire.begin(), but have to #include the <Wire.h> header file.

Finally, I can use a library class function, as in myservo.attach(9), but not only do I need to #include the <Servo.h> header file but I also need to instantiate the class, as in Servo myservo.

Can someone please tell me the difference between these three class function utilizations?

There is a hidden #include <Arduino.h> at the top of you sketch. That's how Serial is available.

The Arduino core provides pre-constructed instances of SerialN. That's why you don't have to create them.

Serial is provided for you because nearly every Arduino application needs Serial for debugging.

You have to add #include <Wire.h> because it's not done for you. It's not done for you because not every application needs the Wire library. The Wire library provides a pre-constructed instance of Wire so you don't have to create it.

Servo is the same as Wire expect that the number of Servo instances is application dependent.

In other words, you are convenienced when it makes sense and have control when it makes sense.

1 Like

Thanks. It is convenient but without any documentation explaining this fact it can be quite confusing for the newbie.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.