How to change a variable inside a class, in a library

Hello.

I am attempting to make a Arduino library. I don't find what I'm looking for in any tutorial I've seen yet.

Inside the library is one class. I want that class to have a variable, which i can change from outside the class. How is this done?

.h

#ifndef Hastighet_h
#define Hastighet_h

#include "Arduino.h"

class Hastighet : 
{
  public:
    static int CHANGE_ME ;
};

#endif

.cpp

#include "Arduino.h"
#include "Hastighet.h"

Hastighet::Hastighet()
{
CHANGE_ME //this is the variable I'd like to change, preferable from the main sketch.
}

Thank you for any response.

As it's static, you would be accessing it in a static context.

Hastighet.CHANGE_ME = 3;

A better way is to use what are called "getters" and "setters". No, they're not types of dog, but functions to get or change an internal class variable:

void Hastighet::setValue(int v) {
  CHANGE_ME = v;
}

int Hastighet::getValue() {
  return CHANGE_ME;
}

// ...

Hastighet myHast;

myHash.setValue(3);

... for example.

Also, as it's static, you may want

static int Hastighet::CHANGE_ME = 0;

in your .cpp to actually create the variable.

majenko: As it's static, you would be accessing it in a static context.

Hastighet.CHANGE_ME = 3;

A better way is to use what are called "getters" and "setters". No, they're not types of dog, but functions to get or change an internal class variable:

void Hastighet::setValue(int v) {
  CHANGE_ME = v;
}

int Hastighet::getValue() {   return CHANGE_ME; }

// ...

Hastighet myHast;

myHash.setValue(3);



... for example.

Also, as it's static, you may want


static int Hastighet::CHANGE_ME = 0; ```

in your .cpp to actually create the variable.

Thank you, majenko. I've experimented a bit now, thanks to you.