1

MyProject.ino:

#include "MyClass.h"
void setup()
{
 Serial.begin(9600);
 // MyClass.MyStaticMethod();
 MyClass::MyStaticMethod();
}

Both uncommented lines work, but the commented (when uncommented, of course) results in this error: expected unqualified-id before '.' token.

Now, I know this is because of the incorrect scope-resolution. Yet, how come Serial manages to call static functions without the need to use :: to correction to scope-resolution.

How come MyClass.MyStaticMethod() doesn't work, but Serial.begin() does?

asked Dec 2, 2016 at 22:05

1 Answer 1

2

. is used to call a method on a class instance whereas :: is used to call a static method within a class itself.

There is no Serial class - Serial is merely an instance of the HardwareSerial class.

#if defined(UBRRH) && defined(UBRRL)
 HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);
#else
 HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
#endif

If you want to use . then you have to instantiate your class and not use a static method:

class MyClass {
 static void myStaticMethod() {
 }
 void myMethod() {
 }
};
MyClass Fred;
// ... 
Fred.myMethod();
MyClass::myStaticMethod();
answered Dec 2, 2016 at 22:19
3
  • Ah. That was quite the misnomer since instances are usually with a lower case. I thought it was a class. :) Commented Dec 2, 2016 at 22:20
  • 1
    That is the normal way, yes - but since when have Arduino done things normally? ;) Commented Dec 2, 2016 at 22:21
  • If a newcomer (myself) is just beginning to see abnormalities, I can't imagine how many you've found. :) Commented Dec 2, 2016 at 22:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.