Home > Net >  Can derived classes call base class constructor with optional parameters?
Can derived classes call base class constructor with optional parameters?

Time:11-07

If I have a base class with a constructor :

class Base{
Base(std::optional<type0> a, std::optional<type1> b, std::optional<type2> c, std::optional<type3> d) : _a(a), _b(b), _c(c), _d(d)  { }

    private:
    std::optional<type0> _a;
    std::optional<type1> _b;
    std::optional<type2> _c;
    std::optional<type3> _d;
};

Can my derived classes derive this constructor with only some of the values and will it automatically map it to the right values? For example if I do:

class Derived{
    Derived(std::optional<type1> b, std::optional<type3> d) : Base(b, d) { }
};

Will it automatically map b to _b and d to _d?

CodePudding user response:

Can my derived classes derive this constructor with only some of the values and will it automatically map it to the right values?

No, you must pass arguments corresponding to each of the parameters of the base class constructor unless some of them have a default argument. This means in your example, in the initializer list of the derived class ctor we should pass 4 arguments corresponding to parameters a, b, c and d of the base' ctor.

CodePudding user response:

Unfortunately it's not the case in C .

You have to pass all the parameters with the same order in definition of Base constructor.

Btw, std::optional is not what you think. Optinal means that variable may or may not contain a value. It doesn't mean that you may not pass values as arguments optionally.

  • Related