I already found many posts talking about this very problem but could not understand any of them. I wanted a simple explanation why this does not work:
class foo {
public:
foo(uint8_t x) {
Serial.begin(115200);
Serial.println(x);
}
};
class bar {
private:
foo foo_1(23); // << I get an error here error: expected ',' or '...' before numeric constant
};
void setup() {
bar bar_1;
}
void loop() {
}
Am I missing something here? I feel like I knew the answer before but every other post regarding problems related to this I can't understand. I wanted the bare minimum example of how to get it to work with "foo" and "bar"
Another thing is, how does this work and the first does not??:
class foo {
public:
foo() {
Serial.begin(115200);
Serial.println(23);
}
};
class bar {
private:
foo foo_1;
};
void setup() {
bar bar_1;
}
void loop() {
}
Any help will be greatly appreciated!
Use curly braces, not parentheses:
foo foo_1 {23};
Or in this case, since you have just a single argument, you could also just use foo foo_1 = 23.
Note that you're specifying a default value for a member variable.
ohhh, now I feel dumb. Thank you very much.
Although, what is the difference between foo foo_1 {23}; and foo foo_1 = foo(23);?
it seems to also work
The former directly initializes the member variable with 23, the latter first creates a temporary foo object, and then copies that to the member variable. Although that copy probably gets elided anyway.
I prefer the first one, because I do not like to repeat the type name foo.
For future reference, initialization in C++ is a complex topic:
https://en.cppreference.com/w/cpp/language/initialization
I was expecting an initializer list to be required:
class foo {
public:
foo(uint8_t x) {
Serial.begin(115200);
Serial.println(x);
}
};
class bar {
public:
bar() : foo_1(23) {}
private:
foo foo_1;
};
void setup() {
bar bar_1;
}
void loop() {
}
Default member initialization is just syntactic sugar that automatically adds the initializer to the initializer lists of all constructors that don't explicitly initialize the member.