Lambda vs inheritance/virtual methods for events

Hey everyone,

I was wondering what your thoughts are no using lambda function vs inheriting and implementing virtual methods.

Lambda seems a bit messy.. but maybe that is just because I am not quite used to using it in C++...

What are your thoughts?
I didn't the connection between lambda, inheriting and virtual methods.
Lambdas are basically function objects (closures?) they are not necessarily related to inheritance and virtual functions. How do we compare these? (unless you have a specific code in mind, where somehow these are connected and can be replaced by one-another)
I am talking about in an event structure...

1
2
3
4
5
6
7
8
9
class Button {
  virtual void onClick() {}
};

class someElement : public Button {
  void onClick() {
    std::cout << "Yay! An Event!\n";
  }
}


Versus...

1
2
3
4
5
6
7
8
class Button {
  std::function<void()> onClick;
};

Button someElement;
someElement.onClick = []()->void {
  std::cout << "Yay! A lambda event!\n";
}
Ah ok.
In this case if the function is going to be useful outside the button class, say button class derives from window class and textbox also derived from window class then it makes more sense for it to be virtual function of window class.

Else if its useful elsewhere, as say generic event handler, then it doesn't hurt to be a named lambda/inline function.
Yeah, I ended up using virtual methods due to readability and neat code. I will probably incorporate lambda into some listeners as well though.. I don't think one is a good replacement for the other.
Topic archived. No new replies allowed.