C++ why can I not access this Class member?

Sorry, this is actually a C++ question, but since I trust you more :blush:

In order to add some functionality to my Touch_4Wire library I’d like to provide external callbacks to respond to drag, click, dblclick events, but I can’t get it to compile when declaring my object like this

TouchClass touchObject(); // pseudo code

A boiled down version of my lib showing my problem would look like this

#include <functional>

class touchEventHandler
        void addHandler(std::function<void(void)> callback)

class touchClass
        touchClass() {} ;
        touchEventHandler* onClick;
        int x;

touchClass* xxx = new touchClass();
touchClass  yyy();

void setup() 
  xxx->onClick->addHandler([]{ xxx->x += 2; }); // this works
  yyy.onClick->addHandler([]{ yyy.x += 3; });   // this gives my the following error
/spark/compile_service/shared/workspace/6_hal_12_0/firmware-privafail.cpp: In function 'void setup()':
/spark/compile_service/shared/workspace/6_hal_12_0/firmware-privafail.cpp:26:7: error: request for member 'onClick' in 'yyy', which is of non-class type 'touchClass()'

/spark/compile_service/shared/workspace/6_hal_12_0/firmware-privafail.cpp: In lambda function:
/spark/compile_service/shared/workspace/6_hal_12_0/firmware-privafail.cpp:26:35: error: request for member 'x' in 'yyy', which is of non-class type 'touchClass()'

What do I do wrong?

Because yyy() is a function, so when you reference yyy.x you are trying to resolve .x from a function type, not an object type (that’s why the error says it’s a non-object type.)

To fix, change yyy.x to yyy().x, or change the declaration of yyy to

touchClass yyy;
1 Like

Darn, I thought this was equivalent but short hand for touchClass yyy = touchClass();

I should have been less lazy and tried the long way :blush:

But thanks that makes sense.