defining classes within a sketch?

Hi-

It seems like it is possible to define a class within a sketch - at least the example code below (from Wiring forum) compiles and trying to instance an object also compiles:

entity ent = entity();

But that is as far as I've been able to go - I have the gist of using classes from other languages but don't know the syntax for defining public functions, etc. in c. Is there a basic example floating around anywhere? I saw the tutorial on creating libraries but would rather work out my class in the sketch before I make a library (or not).

tx!

--Roy

// Code Start --------------
class entity {

  void Set(int foo){

    internal = foo;
  }

  int Get (void) {
    return internal;
  }
   
  int internal;

};
// Code End ---------------

hey roy,

i'm not entirely sure if you can create classes in a sketch... in C++ you need both a header file and a content file that contains the actual code.

a header contains somethign like this:

class entity { public: void Set(int foo); int Get(void); int internal; }

then in your content file you have the actual code.

its actually really easy to create a library file... and then your code is re-usable too!! i highly suggest doing it.

You can also create extra tabs within a sketch using the right-facing arrow button near the top right of the window. Just give them a .cpp or .h extension.

hey tx! working my way through it today and I have been able to define a class and create multiple instances from within a sketch. Yay! Didn't know about the tab feature - will have to check that out.

I can compile an instance of the class below using:

Player red(5, 12);

What I don't know is how to destroy the object- (the example below is just for simplicity - in my actual code I need to do some real cleanup of hardware stuff).

I can't (or don't know how to) call the destructor directly. If I try to set the instance ('red') to void or null or 0, I get compiler errors.

So how do I clear the instance and do the cleanup? Been googling around but haven't seen a useful code example to explicitly clear an object instance. Maybe this is an issue of defining the class in the sketch? Or just a basic c++ thing that I am missing (like that would be hard... ;-)

Coming from a lingo/actionscript background here so I am comfortable with using objects but am running aground with my scant c/c++ knowledge.

--Roy

class Player {
  int health;
  int strength;
  int agility;
public:
  Player(int s, int a) {
    strength = s;
    agility = a;
    health = 10;
  };
  ~Player() {
    strength = 0;
    agility = 0;
    health = 0;
  };
};

The easy way is to let the variable go out of scope. That is, if you create the instance of Player (as with the “red” in your example) inside a function, then the destructor will be called when that function finishes. Otherwise, you might just want to put the cleanup code inside an explicit close() or end() method and call it when you need the cleanup to happen.