Search code examples
c++inheritancevirtual

Function in derived class exactly the same as in base class but different default parameter


In read in this post that you could override a virtual function with other default arguments, but that it is not smart to do. My case is slightly different from the question there. The function in my base class and the function in my derived class should do exactly the same only the default argument is different. How should I go about achieving this?

EDIT with some sort of code example what I think might work but violates what is said in the earlier mentioned post and doesn't seem very neat to me:

class base {
public:
    //not sure about the virtual here
    virtual void func(bool something = true) { /*Do some stuff*/};
};

class derived : public base {
public:
    void func(bool something = false) override
    {
        base::func(something); /*Doesn't seem like the way to go for me */
    }
};

Solution

  • One option is to explicitly overload the function, and not rely on default arguments

     class Base
     {
         public:
             virtual void func() {func(2);}   // call func(int) with one default
             void func(int value);
     };
    
     class Derived: public Base
     {
          public:
             using Base::func;    // so the function which accepts an argument is
                                  //   not hidden from users the class
             virtual void func() {func(42);}    // call Base::func(int) with different value
     };
    

    Depending on need, it may be easier for the default value to be a member that is set by the constructor.

     class Base
     {
         public:
             Base() : default_value(2) {};
             void func() {func(default_value);}
             void func(int value);
    
         protected:
             Base(int defaulted) : default_value(defaulted) {};
    
         private:
             int default_value;
     };
    
     class Derived: public Base
     {
          public:
             Derived() : Base(42) {};    // set different default value in the constructor
     };
    

    Depending on your need (and given that the requirement is only that the function be supplied with different defaults, but are otherwise the same) you may wish to consider leaving the functions non-virtual.