5

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
}
1
  • @MrSmith42: Call site. That's the usual location anyway. Commented Jan 12, 2015 at 13:52

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

In "Effective C++" by Scott Meyers there a chapter called "Never redefine a function's inherited default parameter value". You really shouldn't. You can read the chapter about a very convincing explanations about all the horrors that will happen if you do.

Comments

3

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

Comments

2

You have to redefine it — there's no other way to specify a different default argument. But you can keep the implementation trivial by just 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); }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.