Class and constructor.

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:

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:

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.

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

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

A constructor declaration consists of just the signature.

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.

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.

See Item #5 at the link I previously gave you: When do we use Initializer List in C++? - GeeksforGeeks

If you look at the formal specification and the explanation here, it says:

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.

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

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 !

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 :slight_smile:

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.

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 :

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

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

i can do this :

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

Do i make sense ?

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;

I tried your suggestion and ofcource it works. :slight_smile:
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 :

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);
}

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

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

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

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




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.

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

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

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

This is the declaration and definition of the same constructor:

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

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

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.

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)
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.