Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inherit a function with different default argument values

I would like to inherit a member function without redefining it, but giving it 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
}
like image 667
Xun Yang Avatar asked Jan 12 '15 13:01

Xun Yang


2 Answers

Don’t use defaults, use overloading:

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); }
};

override modifier is C++11.

like image 152
Konrad Rudolph Avatar answered Nov 02 '22 23:11

Konrad Rudolph


No, you can't. But you can implement it like this.

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;
    }
};
like image 40
yunfan Avatar answered Nov 02 '22 22:11

yunfan