Inheritance re-questioned


#1

As I’ve investigated my issue regarding base classes, I’ve found more information and am posting this question in preference - although I’ll leave the other question there as reference.

I’ve taken an example from the documentation and modified it to show what I’m trying to achieve.

The first example here, works fine.

 class Base {
    public:
        void doSomething() {}
    };
    class Derived : public Base {
    };

    Base* myfunction()
    {
        auto b = new Derived();
        return b;
    };

  int main()
    {
        auto chai = std::unique_ptr<chaiscript::ChaiScript>(new chaiscript::ChaiScript(chaiscript::Std_Lib::library()));

        chai->add(chaiscript::base_class<Base, Derived>());
        chai->add(chaiscript::fun(&myfunction), "myfunction");
        chai->add(chaiscript::fun(&Base::doSomething), "doSomething" );
        
        chai->eval(R"_(
                   var obj = myfunction();
                   obj.doSomething();
                  )_");
        
     }

but the second example is what I am trying to do

class Base {
    };
    class Derived : public Base {
    public:
        void doSomething() {}
    };

    Base* myfunction()
    {
        auto b = new Derived();
        return b;
    };

  int main()
    {
        auto chai = std::unique_ptr<chaiscript::ChaiScript>(new chaiscript::ChaiScript(chaiscript::Std_Lib::library()));

        chai->add(chaiscript::base_class<Base, Derived>());
        chai->add(chaiscript::fun(&myfunction), "myfunction");
        chai->add(chaiscript::fun(&Derived::doSomething), "doSomething" );
        
        chai->eval(R"_(
                   var obj = myfunction();
                   obj.doSomething();
                  )_");
        
     }

but that gives me an error

chaiscript::exception::eval_error: Error: “Error with function dispatch for function ‘doSomething’” With parameters: (N9CocosChai4BaseE).()


#2

You have not provided any virtual methods in the Derived class, therefor the compiler does not consider it to be a ‘polymorphic’ class, therefore there’s no way for ChaiScript to know that Base * actually points to a Derived.

The only way for me to know that Base * is actually a Derived is to attempt a reinterpret_cast, which requires a polymorphic type.

As you can see here:

Bidirectional automatic casting is only enabled if the types are polymorphic (again, due to the nature of C++).

Hopefully that makes some sense. Simply add virtual ~Base() = default and the issue will go away.

-Jason


#3

Hey - it makes some sense - but honestly my C++ knowledge is severely limited - I’m really a “user” of chaiscript (which, by the way, is simply fantastic)

I completely understood that bit :slight_smile:

I added that, and it went away!

Awesome!

Thanks @lefticus