Skip to content

Commit 3c94595

Browse files
authored
Create C_and_C++.md
1 parent b798d6e commit 3c94595

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# C++ in the Arduino world
2+
>[!WARNING]
3+
> No details here\
4+
> Just hints on how the Arduino Magic works
5+
>
6+
## More features on top of C
7+
8+
C++ is based on C, has the same syntax, apart from a few exceptions, and adds a few features.
9+
10+
Main improvements concern Object Oriented Programming.\
11+
Thus it is possible to use ***classes*** and ***operator overload***.\
12+
A huge difference concerns functions, by allowing the same function name for different signatures (sets of parameters).\
13+
Example for an object representing a serial port:
14+
```
15+
Serial.begin();
16+
Serial.begin(115200);
17+
```
18+
Overloading operators comes in handy for example for adding Strings:
19+
```
20+
String s1 = "123";
21+
String s2 = "abc";
22+
s1+" "+s2; //ok
23+
```
24+
Memory allocation is handeled with _new_ and _delete_ instead of _malloc_ and _free_.
25+
26+
## Arduino Language
27+
28+
The Arduino language is C++ with a few extras, noticably initializing objects whithout the user having to worry about these details.\
29+
Low-level functions are written in C, which is natural for coding hardware.\
30+
Real genious. Again, using Serial:
31+
```
32+
Serial.begin();
33+
```
34+
Means I can call method begin() of object Serial without having to call the constructor explicitly like I would do in C++:
35+
```
36+
Serial = new SerialClass():
37+
```
38+
In fact this is done in HardwareSerial.h
39+
```
40+
#if defined(UBRRH) || defined(UBRR0H)
41+
extern HardwareSerial Serial;
42+
#define HAVE_HWSERIAL0
43+
#endif
44+
```
45+
Inheritance and polymorphism are widely used for functionality in Arduino.
46+
Once more with Serial:
47+
```
48+
class HardwareSerial : public Stream // inherits Stream
49+
class Stream : public Print // inherits Print
50+
class Print // has no parent
51+
```
52+
💡 So the print methods in Serial class come from Print class.

0 commit comments

Comments
 (0)