Rufus
Rufus

Reputation: 5566

How to avoid changing every child constructor when parent constructor changes

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?

Upvotes: 1

Views: 122

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

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.

Upvotes: 2

Related Questions