Skip to content

How to get instance of sub/child class at runtime? #81

Answered by MatthiasKohl
MatthiasKohl asked this question in Q&A
Discussion options

You must be logged in to vote

So imagine we have this structure in C++ and we want to wrap the functions make_parent and print_stuff overloads:

struct Parent { ... };
struct Child : struct Parent { ... };

Parent* make_parent(bool child) {
  if (child)
    return new Child();
  return new Parent();
}

void print_stuff(Parent& p) { printf("this is a parent\n"); }
void print_stuff(Child& c) { printf("this is a parent\n"); }

If we bind those classes and functions in a straightforward way using nanobind, then call make_parent(True) from python, and then call print_stuff on the result, we'll get "this is a parent".
In pybind, we would get "this is a child" AFAIU

Replies: 2 comments 4 replies

Comment options

You must be logged in to vote
1 reply
@wjakob
Comment options

Comment options

You must be logged in to vote
3 replies
@MatthiasKohl
Comment options

@wjakob
Comment options

@wjakob
Comment options

Answer selected by wjakob
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants