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

339 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

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.

5
On

What you are looking for is the factory design pattern.

Your factory receives the name of the class to instantiate, and any required parameters, then instantiates the appropriate subclass. The name could take the form of a string, an enumerated type, or any other means of selecting the appropriate subclass. Let's use a string:

Eyes *create_eyes(const std::string &color)
{
   if (color == "blue")
          return new BlueEyes;

   if (color == "brown")
          return new BrownEyes;

   throw "Unknown eye color";
}