Code structure to define a class and then to instantiate?

Hello All

I cannot seem to find any documentation regarding defining a class and then instantiating instances of the class in your code.

Is it possible to do this with the arduino, and if so can someone please direct me to a source explaining the structure?


The Arduino installation contains all the source - a useful one to look at is HardwareSerial.cpp and HardwareSerial.h

Thanks for that Awol.

I did a search re defining classes and got a link to creating a library - morse being the example.

So I see I need to create a .h file containing the interface (and private variables??) and a .cpp file containing the implementation.

I assume I do not need to create a library… unless of course I wish to distribute.


I assume I do not need to create a library... unless of course I wish to distribute.

The Arduino definition of a library is a header file with it's associated source file. If you create a .h file and a .cpp file, you have created a library, whether you distribute it or not.


lol - so to define a class one has to create a library :slight_smile:

Well, I guess what works - works.

AgeingHippy: to define a class one has to create a library ...

Here's the thing:

Put all of the .h and .cpp class files in the same directory as your main sketch. They will appear as "tabs" the next time you open the Arduino IDE and open that sketch. You can examine and edit the .cpp and .h files by clicking their tabs. If you include the .h file(s) in your main sketch, Arduino can compile and link everything together.

If you put the .cpp and .h files in a libraries subdirectory, you can import them into any sketch, but you can not open them for examination or modification from within the Arduino IDE.

Bottom line: When developing a library, it may be more convenient to use tabs in a particular sketch. If you want to use that class (or those classes) in any other sketch, copy them into a libraries subdirectory so that you can "import" them from the Arduino IDE.