0

I am python experienced, an arduino noob, and absolutely no experience of C other than what has been forced upon me by arduino use.

I have just spent a day hammering google for the precise syntax of creating and using a class for user libraries, and have finally won.

However, I find that there are two forms that both seem to work for instantiating an object in the main program.

With my python experience, I find it easier to recognise the obj= style, used by Alan Zucconi in his examples, though the arduino.cc library tutorial on the Morse library uses the other form.

Is either preferrable, or are they equivalent in every way? Are there any subtle side effects of which I am unaware, that will bite me if the interfaces get more complicated, or some assumptions get corrected in future releases of the arduino IDE or compiler?

#include "Minimal_library.h"

// allocate buffer to be used
#define BUF_SIZE 40
char buff[BUF_SIZE+1];  

// which of these two instantiation calls works?

// Minimal_library obj = Minimal_library(BUF_SIZE, buff);  //alanzucconi - works
Minimal_library obj(BUF_SIZE, buff);   //  Morse - that seems to work as well now
...

I presume that any private variables defined within the class become fully fledged persistent variables unique to the object created (it's been a long and frustrating day, not quite got around to testing the persistence or uniqueness yet, compiling without error, and then working, are enough for today!)

Neil_UK
  • 404
  • 2
  • 12

1 Answers1

1

The statement

Minimal_library obj(BUF_SIZE, buff);

means “create an object named obj, initialized by calling the class constructor with the supplied parameters”.

On the other hand,

Minimal_library obj = Minimal_library(BUF_SIZE, buff);

means “create an unnamed object initialized as before, then copy it into an object named obj, then delete the unnamed object”.

The compiler would normally optimize the second form into the first one. It is even allowed to do so in some weird cases where they may not be equivalent. In the end, it's mostly a matter of style. I prefer to do the optimization myself and write the first form. But if you find the second form more readable, go ahead: you can normally trust the compiler to optimize out the unneeded copy.

Edgar Bonet
  • 44,999
  • 4
  • 42
  • 81