Funnctors and Polymorphism

I have a design problem that can be solved with the following construction, which uses functors and takes advantage of polymorphism.

#include <iostream>

struct Base {

    virtual void operator()(void) = 0;

};
struct Child1 : Base {

    void operator()(void) {
        std::cout << "I'm child 1\n";
    }
};
struct Child2 : Base {

    void operator()(void) {
        std::cout << "I'm child 2\n";
    }

};

int main (){

    Base *obj = new Child1();
    (*obj)();

    obj = new Child2();
    (*obj)();

}

Base acts as an interface that must be implemented by different classes.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s