2

My goal is to track an array of Plugin objects whenever a plugin is created:

plugin.h

#ifndef PLUGIN_H
#define PLUGIN_H

class Plugin {
public:
  static byte instances;
  static Plugin plugins[];

  Plugin();
  ~Plugin();
};

#endif

plugin.cpp

#include <Arduino.h>
#include "plugin.h"

#define MAX_PLUGINS 3

byte Plugin::instances = 0;
Plugin Plugin::plugins[MAX_PLUGINS];

Plugin::Plugin() {
  Plugin::plugins[Plugin::instances++] = *this;
}

Plugin::~Plugin(){
}

What I've noticed is that

Plugin Plugin::plugins[MAX_PLUGINS];

Already seems to call the plugin constructor which is not what I want as derived Plugins will only be created later in the program. Same happens if I try to create a empty list:

Plugin Plugin::plugins[MAX_PLUGINS] = {};

How can I create a NULL-initialized array of objects of pre-defined but variable length?

Note: I've read Array of objects with constructor but I'm not sure that's possible in the AVR GCC chain?

1 Answer 1

3

By using pointers to Plugin objects in your array instead of actual Plugin objects! This will allow you to zero-initialize the array, then assign pointers to your derived objects as you go.

The method you are trying to do at the moment is flawed, even if you could create an array of objects that aren't 'created' yet.

E.g.

Plugin::Plugin() {
  Plugin::plugins[Plugin::instances++] = *this;
}

This is going to copy the Plugin object, not reference the one you just created.

EDIT for comment: Could you add why {} is instantiating objects?

An empty set of brackets, is called default initialization,

8.5 Initializers To default-initialize an object of type T means:
— if T is an array type, each element is default-initialized;

And then for each element:

— if T is a (possibly cv-qualified) class type (Clause 9), the default constructor (12.1) for T is called...

So basically, the empty constructor (default) is implicitly called for each element.

Sign up to request clarification or add additional context in comments.

2 Comments

Insanely simple. Thank you :) Could you add why {} is instantiating objects?
Yeah, I'll give it a try.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.