Linked Questions

Popular Questions

Suppose I have the following C++ classes:

class Animal {
    public:
    virtual void sound() = 0;
};

class Dog : public Animal {
    public:
    void sound() override {
        std::cout << "Woof\n";
    }
};

class Cat : public Animal {
    public:
    void sound() override {
        std::cout << "Miao\n";
    }
};

std::unique_ptr<Animal> animalFactory(std::string_view type) {
    if (type == "Dog") {
        return std::make_unique<Dog>();
    } else {
        return std::make_unique<Cat>();
    }
}

Is it possible, and if so, how, to write a binding using Pybind11 so that I in Python code can write:

dog = animalFactory('dog')
cat = animalFactory('cat')
dog.sound()
cat.sound()

and have the correct functions in the derived classes called?

Related Questions