Search code examples
c++inheritancepolymorphismvirtual

Polymorphism & default values: can co-exist?


I have a base class with a number of inherited derived classes. Something like this:

class A {
public:
    virtual void f(string foo = "bar") {
        cout << foo << endl;
    }
};

class B: public A {
public:
    void f(string foo = "howdy") {
        cout << foo << endl;
    }
};

class C: public A {
public:
    void f(string foo = "something") {
        cout << foo << endl;
    }
};

I inherited just two classes for brevity.
This is the main:

A* aArray[] = {
    new B,
    new C,
};

int main() {
    aArray[0]->f();
    aArray[0]->f();

    return 0;
}

When I run the program, the output that I get back is:

bar
bar

Just like how if the compiler ignores the default arguments of the overridden functions.
Is this normal, or there is something that I'm doing wrong or that I'm missing?


Solution

  • Default values are statically binded. In other words, they do not have polymorphhic behavior. That's why you saw

     bar
     bar
    

    instead of those default values in the derived classes' virtual functions.

    According to Effective C+:

    If default parameter values were dynamically bound, compilers would have to come up with a way to determine the appropriate default values for parameters of virtual functions at runtime, which would be slower and more complicated than the current mechanism of determining them during compilation.