# Class and constructor.

**URL:** <https://forum.arduino.cc/t/class-and-constructor/653134>\
**Category:** Programming\
**Created:** [May 5, 2020, 8:22am UTC](https://forum.arduino.cc/t/class-and-constructor/653134 "2020-05-05T08:22:49Z")\
**Posts on this page:** 17\
**Page:** 2

<div class="post-metadata">

**Author:** ![HellasT](https://avatars.discourse-cdn.com/v4/letter/h/a88e57/32.png) [@HellasT](https://forum.arduino.cc/u/HellasT)\
**Post date:** [May 13, 2020, 1:43pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/21 "2020-05-13T13:43:05Z")

</div>

Good afternoon.  
I have a question. are these two codes the same? I mean they produce the same outcome but  
code 1 uses initializer lists (like demonstrated in previous posts). Is the writing of code 2 considered initializer list ?  
Is it just a matter of writing style ?

Code 1:

```cpp
class blinker 
{
  public:
    blinker (byte ledPin):ledPin(ledPin) {}
    void begin_();
    void blink_();
  private:
    byte ledPin;
};

blinker LED1(13);

void setup() 
{
  LED1.begin_();
}

void loop() 
{
  LED1.blink_();
}

void blinker::begin_ () 
{
  pinMode (ledPin, OUTPUT);
}

void blinker::blink_() 
{
  digitalWrite (ledPin, HIGH);
  delay (1000);
  digitalWrite (ledPin, LOW);
  delay (1000);
}

```

Code 2:

```cpp
class blinker 
{
  public:
    blinker (byte ledPin);
    void begin_();
    void blink_();
  private:
    byte ledPin;
};

blinker LED1(13);

void setup() 
{
  LED1.begin_();
}

blinker::blinker (byte ledPin):
ledPin(ledPin)
{
  
}

void loop() 
{
  LED1.blink_();
}

void blinker::begin_ () 
{
  pinMode (ledPin, OUTPUT);
}

void blinker::blink_() 
{
  digitalWrite (ledPin, HIGH);
  delay (1000);
  digitalWrite (ledPin, LOW);
  delay (1000);
}

```

Thank you.

---

<div class="post-metadata">

**Author:** ![PieterP](https://avatars.discourse-cdn.com/v4/letter/p/ecccb3/32.png) [@PieterP](https://forum.arduino.cc/u/PieterP)\
**Post date:** [May 13, 2020, 7:45pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/22 "2020-05-13T19:45:06Z")

</div>

A constructor definition consists of three main parts: the signature, the initializer list, and the body.

```cpp
blinker(byte ledPin) : ledPin(ledPin) { /* empty */ }
\--- signature ---/  \- init. list -/ \--- body  ---/

```

A constructor declaration consists of just the signature.

```cpp
blinker(byte ledPin);
\--- signature ---/

```

You can either define the constructor (or any method) inside of the class definition (it is implicitly "inline"), or you can separate the declaration from the definition.

The advantage of moving the definition out of the class is that it can be moved to a separate file, so it can be compiled separately (and in parallel). If you leave it in the class, it's in a header file, so it has to be compiled every time you include that header.  
For small methods like your constructor, this is not an issue, and you'll probably want to keep it inline, so the compiler has more opportunities for optimization.

Your first example defines the constructor inside of the class, i.e. inline.  
Your second example declares the constructor inside of the class, but defines it outside of the class.  
Since the definition is in the same file as the declaration, there's really no advantage to using the second code.

---

<div class="post-metadata">

**Author:** ![HellasT](https://avatars.discourse-cdn.com/v4/letter/h/a88e57/32.png) [@HellasT](https://forum.arduino.cc/u/HellasT)\
**Post date:** [May 13, 2020, 8:17pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/23 "2020-05-13T20:17:11Z")

</div>

I understand !

Something that strikes me as strange in code 1

How come that the below piece of the code does not cause name colission ?

blinker (byte ledPin):ledPin(ledPin) {}

variable ledPin taking itself as argument ? I am not sure i understand that correctly.

---

<div class="post-metadata">

**Author:** ![gfvalvo](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gfvalvo/32/1013044_2.png) [@gfvalvo](https://forum.arduino.cc/u/gfvalvo)\
**Post date:** [May 13, 2020, 8:27pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/24 "2020-05-13T20:27:47Z")

</div>

See Item #5 at the link I previously gave you: [When do we use Initializer List in C++? - GeeksforGeeks](https://www.geeksforgeeks.org/when-do-we-use-initializer-list-in-c/)

---

<div class="post-metadata">

**Author:** ![PieterP](https://avatars.discourse-cdn.com/v4/letter/p/ecccb3/32.png) [@PieterP](https://forum.arduino.cc/u/PieterP)\
**Post date:** [May 13, 2020, 8:32pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/25 "2020-05-13T20:32:50Z")

</div>

If you look at the formal specification and the explanation [here](https://en.cppreference.com/w/cpp/language/initializer_list), it says:

> ```arduino
> class-or-identifier ( expression-list(optional) )
> 
> ```
> 
> Initializes the base or member named by class-or-identifier using direct initialization or, if expression-list is empty, value-initialization  
> [...]  
> Names that appear in expression-list or brace-init-list are evaluated in scope of the constructor

This means that the identifier outside of the parentheses refers to the member variable. Everything else (between the parentheses, and inside of the constructor body) refers to the variable in the current scope, i.e. the parameter.

```arduino
blinker (byte ledPin) : ledPin(ledPin) {}
                         │      └───────── parameter (expression-list)
                         └──────────────── member (class-or-identifier)

```

Also see the example in the "Explanation" section: [Constructors and member initializer lists - cppreference.com](https://en.cppreference.com/w/cpp/language/initializer_list#Explanation)

---

<div class="post-metadata">

**Author:** ![HellasT](https://avatars.discourse-cdn.com/v4/letter/h/a88e57/32.png) [@HellasT](https://forum.arduino.cc/u/HellasT)\
**Post date:** [May 13, 2020, 9:17pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/26 "2020-05-13T21:17:38Z")

</div>

Thank you both gfvalvo and PieterP.  
I now need to study the links. I will post back if i need more assistance.

Have a good night !

---

<div class="post-metadata">

**Author:** ![HellasT](https://avatars.discourse-cdn.com/v4/letter/h/a88e57/32.png) [@HellasT](https://forum.arduino.cc/u/HellasT)\
**Post date:** [April 24, 2021, 7:43pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/27 "2021-04-24T19:43:29Z")

</div>

Hello everyone !

I have some issues i try to figure out that do concern the previous posts here so i thought not to cloud the forum with a new topic rather than revive this old one. I hope its not a bad call 🙂

I took the code from post #11 and i want to modify it a bit. To be more spesific:  
The current code will blink a led every second. the class has one object called LED1 that takes the pin number as argument.

```cpp
class blinker 
{
  public:
    blinker (byte ledPin) : _ledPin(ledPin) {}
    void begin();
    void blink();
  private:
    byte _ledPin;
};

blinker LED1(13);

void setup() 
{
  LED1.begin();
}

void loop() 
{
  LED1.blink();
}

void blinker::begin () 
{
  pinMode (_ledPin, OUTPUT);
}

void blinker::blink() 
{
  digitalWrite (_ledPin, HIGH);
  delay (1000);
  digitalWrite (_ledPin, LOW);
  delay (1000);
}

```

How can i modify the code so i can pass the pin number as argument not to the object but to the begin() function so that instead of this :

```cpp
class blinker 
{
  public:
    blinker (byte ledPin):_ledPin(ledPin){} 
    void begin ();
    void blink();
  private:
    byte _ledPin;
};

blinker LED1(13); // <---

```

i can do this :

```cpp
void setup() 
{
  LED1.begin(13); // <---
}

```

Do i make sense ?

---

<div class="post-metadata">

**Author:** ![killzone\_kid](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/killzone_kid/32/1098074_2.png) [@killzone\_kid](https://forum.arduino.cc/u/killzone_kid)\
**Post date:** [April 25, 2021, 5:57am UTC](https://forum.arduino.cc/t/class-and-constructor/653134/29 "2021-04-25T05:57:04Z")

</div>

make begin() take an argument which is a pin number

begin(byte pinnum)

and set the pin in the object in the body of the begin

ledpin = pinnum;

---

<div class="post-metadata">

**Author:** ![HellasT](https://avatars.discourse-cdn.com/v4/letter/h/a88e57/32.png) [@HellasT](https://forum.arduino.cc/u/HellasT)\
**Post date:** [April 25, 2021, 3:26pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/30 "2021-04-25T15:26:34Z")

</div>

I tried your suggestion and ofcource it works. 🙂  
I have such a poor programming knowledge. I thought that every class is mandatory to have a constructor default or not.  
In this case i had to delete the constructor to make it work. take a look :

```cpp
class blinker 
{
  public:
    //blinker ();
    void begin(byte ledPin);
    void blink();
  private:
    byte _ledPin;
};

blinker LED1;

void setup() 
{
  LED1.begin(13);
}

void loop() 
{
  LED1.blink();
}

void blinker::begin (byte ledPin) 
{
  _ledPin = ledPin;
  pinMode (_ledPin, OUTPUT);
}

void blinker::blink() 
{
  digitalWrite (_ledPin, HIGH);
  delay (1000);
  digitalWrite (_ledPin, LOW);
  delay (1000);
}

```

---

<div class="post-metadata">

**Author:** ![killzone\_kid](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/killzone_kid/32/1098074_2.png) [@killzone\_kid](https://forum.arduino.cc/u/killzone_kid)\
**Post date:** [April 25, 2021, 3:57pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/31 "2021-04-25T15:57:05Z")

</div>

Well, you deleted custom constructor, but default constructor is still called with no arguments even if you did not explicitly define it.

---

<div class="post-metadata">

**Author:** ![HellasT](https://avatars.discourse-cdn.com/v4/letter/h/a88e57/32.png) [@HellasT](https://forum.arduino.cc/u/HellasT)\
**Post date:** [April 25, 2021, 4:41pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/32 "2021-04-25T16:41:22Z")

</div>

In other words, i should not create a default constructor since the default constructor is automatically created by the compiler yes ?  
Thank you !

---

<div class="post-metadata">

**Author:** ![jimLee](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/jimlee/32/214865_2.png) [@jimLee](https://forum.arduino.cc/u/jimLee)\
**Post date:** [April 25, 2021, 6:06pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/33 "2021-04-25T18:06:43Z")

</div>

Its not a rule. It can be nice to have a constructor that does nothing. I like having them in my classes to at a glance I can see that "Oh yeah, I didn't do anything special here". Instead of looking around for code that isn't there. Some would like to have them, some not. Not a rule, just how you'd like to do it.

-jim lee

---

<div class="post-metadata">

**Author:** ![HellasT](https://avatars.discourse-cdn.com/v4/letter/h/a88e57/32.png) [@HellasT](https://forum.arduino.cc/u/HellasT)\
**Post date:** [April 25, 2021, 7:18pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/34 "2021-04-25T19:18:17Z")

</div>

I understand though i get a little strage behaviour from the IDE. When i uncomment the default constructor then i get the following error from the IDE

```cpp

C:\Users\CONSTA~1\AppData\Local\Temp\ccvZRI1v.ltrans0.ltrans.o: In function `global constructors keyed to 65535_0_sketch_apr25b.ino.cpp.o.1746':
<artificial>:(.text.startup+0x5c): undefined reference to `blinker::blinker()'
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino Uno.

```

---

<div class="post-metadata">

**Author:** ![PieterP](https://avatars.discourse-cdn.com/v4/letter/p/ecccb3/32.png) [@PieterP](https://forum.arduino.cc/u/PieterP)\
**Post date:** [April 25, 2021, 7:20pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/35 "2021-04-25T19:20:52Z")

</div>

You didn't define the constructor, you only declared it.

This is the declaration of a constructor that takes no arguments:

```cpp
class blinker {
  blinker();
  ...
};

```

This is the declaration and definition of the same constructor:

```cpp
class blinker {
  blinker() = default;
  ...
};

```

The `= default;` is the actual definition of the function. Another definition could be `{}`.

---

<div class="post-metadata">

**Author:** ![dsebastian](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/dsebastian/32/1099263_2.png) [@dsebastian](https://forum.arduino.cc/u/dsebastian)\
**Post date:** [April 28, 2021, 3:12pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/36 "2021-04-28T15:12:06Z")

</div>

> [@UKHeliBob](#):
>
> It is good practice for the object to be created by the constructor globally then for there to be a begin() method called from inside setup() that initialise the object with pin numbers etc. Doing it this way ensures that the hardware is ready before setting pinMode()s etc If you do that in the constructor then there is a chance that the hardware is not ready

Even though quite a long time ago, but I like to understand the mechanism behind. Not just applying this practice.  
Isn't it that the µ-controller - in particular in case it is just one and when it is about the controllers I/Os etc - the hardware (i.e. the controller) is always ready before the controller can begin with the execution of a program? So, when we talk about, e.g. an GPIO of an ATMega328P from an Uno-board ... what is preventing the ATMega328P from properly configuring its GPIO while it simultaneously can execute code?  
I hope on some insights - thanks.

---

<div class="post-metadata">

**Author:** ![PieterP](https://avatars.discourse-cdn.com/v4/letter/p/ecccb3/32.png) [@PieterP](https://forum.arduino.cc/u/PieterP)\
**Post date:** [April 28, 2021, 3:28pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/37 "2021-04-28T15:28:45Z")

</div>

The hardware is configured by the software. The Arduino Core initializes some of the peripherals at the beginning of the `main` function. Constructors of global variables execute before `main`, if you try to use these peripherals before they are configured, your program often won't work correctly.

On AVR, the peripherals are quite simple, and not a whole lot of configuration is necessary, mostly timers for `millis` and PWM, the ADC prescaler, and TX/RX pins. ([ArduinoCore-avr/wiring.c at 6ec80154cd2ca52bce443afbbed8a1ad44d049cb · arduino/ArduinoCore-avr · GitHub](https://github.com/arduino/ArduinoCore-avr/blob/6ec80154cd2ca52bce443afbbed8a1ad44d049cb/cores/arduino/wiring.c#L241-L392))  
Writing to GPIO registers on AVR before `main` is probably not an issue.  
More advanced ARM CPUs require much more configuration, such as configuring the MMU, selecting the clocks and prescalers for each peripheral, enabling these peripherals, configuring interrupts, etc.

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [August 26, 2021, 3:29pm UTC](https://forum.arduino.cc/t/class-and-constructor/653134/38 "2021-08-26T15:29:21Z")

</div>

Closed on August 26, 2021, 3:29pm UTC

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

[Previous page](https://forum.arduino.cc/t/class-and-constructor/653134.md?page=1)
