Brandon
Brandon

Reputation: 23498

Pure Virtual function override

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

Upvotes: 3

Views: 769

Answers (5)

juanchopanza
juanchopanza

Reputation: 227390

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(); };

Upvotes: 4

Sellorio
Sellorio

Reputation: 1950

You can instead store a function pointer called show in the class.

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

Then if Show != 0 you can call it (aka if the user assigns a function pointer to it).

Upvotes: 2

Nbr44
Nbr44

Reputation: 2062

Something like that can work :

#include <functional>
#include <iostream>

class Foo
{
public:
  std::function<void(void)> Show;
};

int main()
{
  Foo f;

  f.Show = [&] () { std::cout << "Hello !" << std::endl; };
  f.Show();
}

Upvotes: 3

Mankarse
Mankarse

Reputation: 40603

The closest you can get is a local anonymous class:

#include <iostream>
class Foo
{
    public:
        virtual void Show() = 0;
};
int main() {
    struct : Foo {
        void Show() {
            std::cout << "Hello world\n";
        }
    } f;
    f.Show();
}

Upvotes: 2

fatihk
fatihk

Reputation: 7919

Pure virtual classes can not be instantiated at all

Upvotes: 2

Related Questions