Search code examples
c++c++11object-composition

Is it possible to use C++ object composition where choice of object is determined at run-time?


Say I have a class Face. I wish to use composition to build Face. Face has eyes, so I can create a class Eyes and use composition adding eyes to Face.

But what if I subclass eyes, e.g.

class Eyes { ... };
class BlueEyes : public Eyes { ... };
class BrownEyes : public Eyes { ... };

? (Assume interfaces are all identical.)

Is it possible to compose Face at run-time, say depending on some parameter provided to the constructor a Face would get either BlueEyes or BrownEyes?


Solution

  • You can do this by composing a pointer to the base class. E.g.,

    enum EyeColor{Blue, Brown}; // Even better would be enum class
    
    class Face
    {
    private:
        // Here is the composition - to a base-class ptr.
        std::unique_ptr<Eyes> m_eyes;
    
    public:
        explicit Face(EyeColor c) 
        {
            // Use c to instantiate m_eyes below to the appropriate-class object.
        }
    };
    

    In fact, the C++ implementation of some design patterns, e.g., Strategy, often employ this.