0

Supposing a general player that will notify certain events to certain objects of classes. I create a base class with some virtual functions guaranteed to exist in the derived:

class PlayEventsReceiver{

    virtual void StartPlay()=0;
    virtual void StopPlay()=0;  
};

I would derive from PlayEventsReceiver the classes interested in such "signals"

class FooPlayer:public PlayEventsReceiver{

    void StartPlay(){...}
    void StopPlay(){...}
};

But if I wanted, rather than inheriting, implementing the signaling mechanism as a property, like this:

class BarPlayer{

    PlayEventsReceiver receiver; 

};

Is it possible to implement the pure virtual functions somehow inside the class BarPlayer in a clean way and not creating intermediate derived classes?

3
  • No because you can't instantiate a virtual class, so you have to create an intermediate derived class. Commented Aug 18, 2015 at 17:34
  • If you could come up with a way to "implement the pure virtual functions somehow inside the class BarPlayer" how would it be more clean than simply making BarPlayer inherit the interface and supply its own implementations? Commented Aug 18, 2015 at 17:40
  • @Galik, I was just experimenting a concept new to me, "Composition over inheritance" en.wikipedia.org/wiki/Composition_over_inheritance Commented Aug 19, 2015 at 9:28

1 Answer 1

1

If you don't have a derived class then the compiler has nowhere to put its functions. If you are looking for something clean then creating an explicit derived class is probably as clean as it gets.

You can't escape the fact that somewhere you need to supply the function implementations.

However, it seems you can do this anonymously by creating an unnamed class/struct. But it is not avoiding creating a derived class because an anonymous derived class is still being created:

// public interface so I use struct
struct PlayEventsReceiver {

    virtual void StartPlay() = 0;
    virtual void StopPlay() = 0;
};

class BarPlayer {

public:
    struct : PlayEventsReceiver {

        void StartPlay() override
        {
            std::cout << "Start Play\n";
        }
        void StopPlay() override
        {
            std::cout << "Stop Play\n";
        }
    } receiver;

};

int main()
{
    BarPlayer bp;

    bp.receiver.StartPlay();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's what I was looking for. If I am not missing anything, there's not a clear way to access the outer class, only passing a pointer to the container in the constructor of the inner making things a more complicated than simply inheriting the PlayEventsReceiver.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.