Classes

Exposing a C++ class to CliPP is the next step.

Here is a small example

    class accumulator : public object {
    private:
	double total;
	int count;
    public:
	accumulator() { total = 0.0; count=0;}
	void add_in(double n) {total+=n; count++;}
	int number() { return count; }
	double mean() { return total/count; }
	static void init(context* c);
    };

It is convenient to let all classes you want to expose to the scripting engine inherit from object. the object class implements garbage collection, and ensures proper memory management. If you have a c++ class that you want to expose to the scripting, you have to think about how you want CliPP to manage instances of that class, when it is created or returned from function calls. More on thin in the chapter Storage policies.

If you choose to make your class inherit from object, you must implement a static  init function with the above signature. This is to allow automatic initialisation of function arguments (see Automatic type registering)

The init function will expose the class to javascript.

    void accumulator::init(context* c)
    {
	//Define class
	class_<accumulator,object> cls("accumulator",c);
	//Define constructors	
	cls.constructor(arguments<>());
	//Define functions
	cls.function("add_in",add_in);
	//Define properties
	cls.read("number",number);
	cls.read("mean",mean);
    }

Again, you can access this directly in the javascript parser:

	parser.parse("var a=accumulator();"
	             "a.add_in(5);"
	             "a.add_in(7);"
	             "var b=a.mean;");