Why does my Arduino Class Constructor require an argument?

I am writing a very simple Arduino class for controlling two motors.

I have the simplest class definition inside my Motor.h header file:

class Motor { public: Motor(); void left(int speed); void right(int speed); void setupRight(int rightSpeed_pin, int rightDirection_pin); void setupLeft(int leftSpeed_pin, int leftDirection_pin); private: int _rightMotorSpeedPin; int _rightMotorDirectionPin; int _leftMotorSpeedPin; int _leftMotorDirectionPin; }; 

In my main library file, Motor.cpp, I have the following class constructor:

 Motor::Motor() { // Intentionally do nothing. } 

When I try to initialize my class in my main program using the line:

 Motor motor(); 

I get the following compilation error:

 MotorClassExample.ino: In function 'void setup()': MotorClassExample:7: error: request for member 'setupRight' in 'motor', which is of non-class type 'Motor()' MotorClassExample:8: error: request for member 'setupLeft' in 'motor', which is of non-class type 'Motor()' request for member 'setupRight' in 'motor', which is of non-class type 'Motor()' 

The incomprehensible part is that if I even include garbage by dropping an argument into the Motor Class constructor as follows:

 class Motor { public: Motor(int garbage); ... 

And in the .cpp file:

 Motor::Motor(int garbage) { } 

And in my main file:

 Motor motor(1); 

Everything works fine without complaint. I searched quite a bit on the Arduino forums, but did not find anything to explain this strange behavior. Why does the class constructor need an argument? Is this some kind of weird relic related to AVR or something like that?

+5
source share
2 answers

You are faced with the problem of "the most annoying parsing" (named so because it is annoying, of course).

Motor motor(); declares a function called motor that takes no arguments and returns a motor . (No different from int test(); or similar)

To define an instance of motor called motor , use Motor motor; without parentheses.

+8
source

In addition to the accepted answer:

With C ++ 11, you can use the syntax of "uniform initialization". The advantage of uniform initialization over a functional form is that curly braces cannot be confused with function declarations that occurred in your case. The syntax can be used as functional, except that you use curly braces {} .

There are some good examples here.

 Rectangle rectb; // default constructor called Rectangle rectc(); // function declaration (default constructor NOT called) Rectangle rectd{}; // default constructor called 
+3
source

Source: https://habr.com/ru/post/1237710/


All Articles