sol2 icon indicating copy to clipboard operation
sol2 copied to clipboard

Can't call constructor of a derived class

Open jacodiego opened this issue 2 years ago • 1 comments

Hello, i am having a problem, when i try to call the constructor of a derived class, here the case in synthesis:

c++

class GameScreen
    {
    public:
        GameScreen();
        GameScreen(ScreenType);
    };

class MapScreen : public screen::GameScreen
    {
    public:
        MapScreen();
    };

sol::table screen_module = lua["screen"].get_or_create<sol::table>();
        screen_module.new_usertype<GameScreen>("GameScreen", sol::constructors<GameScreen(), GameScreen(ScreenType)>());

sol::table map_module = lua["map"].get_or_create<sol::table>();
        map_module.new_usertype<map::MapScreen>("MapScreen", sol::constructors<>(),
                                                sol::base_classes, sol::bases<screen::GameScreen>());

lua

-- This is OK
print("pointer to class: ", screen.MapScreen);

-- This fail
print("call constructor: ", screen.MapScreen:new());

Could i be forgetting something?

Regards

jacodiego avatar Feb 17 '23 19:02 jacodiego

Maybe you should call screen.MapScreen.new(), so with . instead of :. You are also using screen while the example code looks like it should use map. Looks like your example code has some missing code. It is hard to know if some of it causes your problems.

I tested your example and made it work in godbolt, so you can try take a look and see how your code differs.

#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

typedef int ScreenType;

class GameScreen {
   public:
    GameScreen() {}
    GameScreen(ScreenType) {}
};

class MapScreen : public GameScreen {
   public:
    MapScreen(){};
};

int main() {
    // Sol
    sol::state lua;
    lua.open_libraries(sol::lib::base, sol::lib::package);

    sol::table screen_module = lua["screen"].get_or_create<sol::table>();
    screen_module.new_usertype<GameScreen>(
        "GameScreen",
        sol::constructors<GameScreen(), GameScreen(ScreenType)>());

    sol::table map_module = lua["map"].get_or_create<sol::table>();
    map_module.new_usertype<MapScreen>("MapScreen", sol::constructors<MapScreen()>(),
                                       sol::base_classes,
                                       sol::bases<GameScreen>());

    lua.script("print('pointer to class: ', map.MapScreen);");
    lua.script("print('call constructor: ', map.MapScreen.new());");

    return 0;
}

Rochet2 avatar Feb 17 '23 21:02 Rochet2