About ChaiScript

ChaiScript is the first and only scripting language designed from the ground up with C++ compatibility and modern design in mind. It is an ECMAScript-inspired, embedded functional-like language.

ChaiScript is licensed under the BSD license.

Download

Due to an increased release schedule, and the nature of ChaiScript being a header-only library, binary releases will be made less often. Previous releases can be found on github.

Version: 4.2.0 Released: 12/1/2012
(Requires Boost)
Source (tar.bz2)
Source (zip)

Version: 5.2.0 Released: 12/1/2012
(Requires C++11 Compiler)
Source (tar.bz2)
Source (zip)

Call method of derived class from base class pointer

I have an global object that can return object pointer pointer of some "Base" class, but sometimes it return base class pointer to a derived object. In derived class i have some addition method and want to call it.
In C++ it seems something like this:

#include "chaiscript/chaiscript.hpp"
 
using namespace chaiscript;
 
class Base {};
class Derived: public Base
{
public:
    void newMethod() {}
};
 
int
main()
{
    ChaiScript chai;
    chai.add(user_type<Base>(), "Base");
    chai.add(user_type<Derived>(), "Derived");
    chai.add(fun(&Derived::newMethod), "newMethod");
    Base* d = new Derived();
    chai.add(var(d), "d");
    chai.eval("d.newMethod()"); //<-- Can i somehow do this without errors?
}

There is a way to do this?

PS: Sorry for bad English

This is not going to work for

This is not going to work for the same reason it would not work in C++.

Base *d = new Derived();
d->newMethod(); // no such method

In C++ you'd have to cast to the derived time, in ChaiScript you will have to do the same, with a method you provide. Example:

Derived &toDerived(Base &b)
{
  return dynamic_cast<Derived &>(b);
}
 
chai.add(fun(&toDerived), "toDerived");
chai.eval("toDerived(base).newMethod()");

I use this way, but i hope

I use this way, but i hope there is a better one =)
Thanks anyway)
Do you plan to do think such that? or it goes against the principles of chaiscript?

Because ChaiScript is so

Because ChaiScript is so closely linked to C++, it wouldn't make sense to automatically go from a base class object to a derived object.

Example:

class Base
{
  public:
    void myFunc();
};
 
class Derived : public Base
{
  public:
    void myFunc();
};
 
int main()
{
  Base *b = new Derived();
 
  // Note, myFunc is NOT virtual. This means that
  // the next line calls Base::myFunc(). We want to preserve
  // this behavior as it exists in C++
  b->myFunc();
}

Besides the above example, it would add more overhead in trying to guess what the user intended.

-Jason

Support ChaiScript by sharing it with your friends: