Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure Virtual function override

Tags:

c++

Ok so I have a bit of a silly question but I think it might be useful if there was a way to do it.

Anyway, assume I have the following class:

class Foo
{
    public:
        virtual void Show() = 0;
};

What if I want to use Foo without inherriting? Is there a way to simply do the following (rather than create a whole new class to implement Show):

Foo F;
F.Show = [&]{/*Do something here*/}; //Assign some function or Lambda to Foo instance F

Is there a way to do that? I know it seems silly but I just have to know if that or something similar can be done.

It obviously doesn't compile :l

like image 517
Brandon Avatar asked Aug 05 '26 17:08

Brandon


1 Answers

Is there a way to do that?

No, you can't instantiate Foo if it has a pure virtual member function.

I just have to know if that or something similar can be done.

It depends what you mean by similar. If you forget about the pure virtual, you can give Foo::Show() an implementation in terms of, say, an std::function<void()>, which you can set from a lambda expression, another std::function<void()> or any callable entity with that signature and return type.

#include <functional>
class Foo
{
 public:
  virtual void Show() { fun(); }
  std::function<void()> fun;
};

Then

#include <iostream>
int main()
{
  Foo f;
  f.fun = []{std::cout << "Hello, World!";};
  f.Show();
}

Note as suggested in @MrUniverse's comment, you should check whether the function has been assinged before calling it. This can be easily done:

virtual void Show() { if (fun) fun(); };
like image 78
juanchopanza Avatar answered Aug 08 '26 08:08

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!