1

Say I have the following (C++)

class Parent
{
     Parent(Foo f){};
}

class Child : public Parent
{
    Child(Foo f, Bar b)
        : Parent(f)
    {};
}
...
// And a whole bunch of other children, all calling Parent constructor

Suppose now I need to add a new parameter to the Parent constructor

Parent(Foo f, Baz z){};

Then I will have to change every single child class to the following

Child(Foo f, Baz z, Bar b)
    : Parent(f, z)
{};

Is there anyway I can avoid having to change every single child class?

Guess might be related to this, how to avoid repetitive constructor in children which suggests that I must change every child class.

If so, are there any languages / design patterns that would make such a change less painful?

Community
  • 1
  • 1
Rufus
  • 5,111
  • 4
  • 28
  • 45
  • 1
    Do the child classes use the new parameter in any way? If not then let the parent have two constructors. – Jonny Henly Apr 25 '16 at 05:31
  • If you have so many subclasses that this is actually a chore, there's a fair chance that you should reconsider your design instead. – molbdnilo Apr 25 '16 at 06:00

1 Answers1

2

If the new argument to the parent constructor is mandatory then there really no choice, you have to update the child classes constructors.

But if the new argument is not mandatory, just add the new parent constructor as an overloaded constructor, or use a default value for the new argument.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621