is it ok to use dynamic bind to implement polymorphism instead of pointer?

63 Views Asked by At

generally in c++ we use virtual class and pointers to achieve polymorphism, but recently I accidently made it with dynamic binding with std::function

sample:


class base {
using func_t = std::function<void()>;
private:
    func_t func_;

public:
    void foo() {
        func_();
    }
    void set(func_t func) {
        func_ = std::move(func);
    } 
};

class derived : public base{
public:
    // something_else
};

void caller(base& b) {
    b.foo();
}

void test() {
    derived d;
    d.set([]() {
        printf("test\n");
    });
    caller(d);
}

this code would work, but is it safe? or just rely on the implementation?

0

There are 0 best solutions below