C ++ inherits a function with different default argument values

I would like to inherit a member function without overriding it, but providing it with different default values. What should I do?

class Base{
  public:
    void foo(int val){value=val;};
  protected:
    int value;
};

class Derived : public Base{
  public:
    void foo(int val=10);
};

class Derived2 : public Base{
  public:
    void foo(int val=20);
};

void main(){
   Derived a;
   a.foo();//set the value field of a to 10
   Derived2 b;
   b.foo();//set the value field of b to 20
}
+4
source share
4 answers

Do not use default values, use overload:

class Base{
    public:
        virtual void foo() = 0;

    protected:
        void foo(int val) { value = val; }

    private:
        int value;
};

class Derived : public Base {
    public:
        void foo() override { Base::foo(10); }
};

class Derived2 : public Base {
    public:
        void foo() override { Base::foo(20); }
};
Modifier

override is C ++ 11.

+6
source

Scott Meyers' Effective C ++ has a chapter entitled "Never Override a Function That Inherits the Default Value of a Parameter." You really shouldn't. You can read the chapter on very compelling explanations about all the horrors that will happen if you do.

+2
source

, . .

class Base{
public:
    virtual int getDefaultValue() = 0;
    void foo(){value = getDefaultValue();};
protected:
    int value;
};

class Derived : public Base{
public:
    int getDefaultValue() {
        return 10;
    }
};

class Derived2 : public Base{
public:
    int getDefaultValue() {
        return 20;
    }
};
+2

You need to override it. There is no other way to specify a different default argument. But you can keep the implementation trivial just by calling the base version:

class Base{
  public:
    void foo(int val){value=val;};
  protected:
    int value;
};

class Derived : public Base{
  public:
    void foo(int val=10) { Base::foo(val); }
};

class Derived2 : public Base{
  public:
    void foo(int val=20) { Base::foo(val); }
};
+1
source

Source: https://habr.com/ru/post/1570877/


All Articles