Hello!
I am reading about constructors and different ways to initialize class member variables within the constructors. There is a nice summary from anon46966594 in this thread: Best practice when initialising class variables - #10 by Boffin, which I rewrite below:
Using “this” keyword:
foo(int bar1, int bar2, int bar3)
{
this->bar1=bar1;
this->bar2=bar2;
this->bar3=bar3;
};
Using “” or 'm' for member variables:
foo(int bar1, int bar2, int bar3)
{
m_bar1=bar1;
m_bar2=bar2;
m_bar3=bar3;
};
Using member initializer list:
foo(int bar1, int bar2, int bar3)
: bar1(bar1), bar2(bar2), bar3(bar3)
{};
However, I am unclear about assigning default values for these different methods.
I have tried this (I will paste the full code below):
Person(){}
Person(int age);
Person(int age , int size = 11);
It compiles if I create an object with two arguments (ie Jack 33, 45), but will give an error (call of overloaded 'Person(int)' is ambiguous Person jack (33)) if I use only one parameter, expecting the program to assign the default value to the size variable.
I have been looking around for some examples and found this library which sort of confused me even further (it’s a pushbutton library from github: pushButton/pushButton.h at main · italo-coelho/pushButton · GitHub)
In the H file the code is:
public:
pushButton(uint8_t pin);
pushButton(uint8_t pin, uint16_t debounce, uint8_t pin_mode = PIN_MODE);
in the CPP files the constructors are:
pushButton::pushButton(uint8_t pin)
{
_pin = pin;
_pinMode = PIN_MODE;
_debounce = DEBOUNCE;
pinMode(_pin, _pinMode);
}
pushButton::pushButton(uint8_t pin, uint16_t debounce, uint8_t pin_mode)
{
_pin = pin;
_pinMode = pin_mode;
_debounce = debounce;
pinMode(_pin, _pinMode);
}
So the PIN_MODE default value is not there anymore in the CPP file (why?). Also this code uses the same method that I use in my code to assign default value to a variable, but my code would not compile (with “= 33” added to the size argument).
my full code is the one below:
class Person{
private:
int _age;
int _size;
public:
Person(){}
Person(int age);
Person(int age , int size);
// Person(int age , int size = 11); the code wouldnot compile with this line in place of the one above
};
Person::Person(int age){
_age = age;
Serial.print("Person age: "); Serial.println(_age);
Serial.print("Person size: "); Serial.println(_size);
}
Person::Person(int age , int size){
_age = age;
_size = size;
Serial.print("Person age: "); Serial.println(_age);
Serial.print("Person size: "); Serial.println(_size);
}
void setup() {
Serial.begin(115200);
Person john(55, 55);
Person jack (33);
}
void loop() {
}