Search code examples
c++inheritanceconstructorcomposition

How to initialize member objects that requires constructor parameters in derived classes?


I would like to include a Composed object in my Base class, and have different derived classes have different configurations of it. However the Composed class requires parameter in constructor, and I don't have control over its architecture.

The compiler is reporting an error because the parameter for Composed should be passed at the initialization of Base class. But I only want it to be initialized in derived classes. What should I do in this case?

class Base{
  public:
    Base(); //Error
  protected:
    Composed comp;
};
class Composed{
  public:
    Composed(int id):id(id);
  private:
    int id;
};
class Derived_1:public Base{
  public:
    Derived():comp(1234){};
};    
class Derived_2:public Base{
  public:
    Derived():comp(2345){};
};   

Solution

  • You'll have to pass that parameter up to Base, and then hand it down to comp:

    class Composed{
      public:
        Composed(int id):id(id);
      private:
        int id;
    };
    class Base{
      public:
        Base(int id):comp(id){}
      protected:
        Composed comp;
    };
    class Derived_1:public Base{
      public:
        Derived():Base(1234){};
    };    
    class Derived_2:public Base{
      public:
        Derived():Base(2345){};
    };