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?

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();
  • Ah. That was quite the misnomer since instances are usually with a lower case. I thought it was a class. :) – Fine Man Dec 2 '16 at 22:20
  • 1
    That is the normal way, yes - but since when have Arduino done things normally? ;) – Majenko Dec 2 '16 at 22:21
  • If a newcomer (myself) is just beginning to see abnormalities, I can't imagine how many you've found. :) – Fine Man Dec 2 '16 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.