3

Why is this printing 23 as output; my expectation was 33. Could somebody please shed some light on this.

struct A {
    virtual void f() {cout << "1";}
};

/* Private inheritance */
struct B : private A {
    void f(int x = 0) {cout << "2";}
};

struct C : B {
    void f(){cout << "3";}
};

int main() {
    C obj;
    B &ref = obj;
    ref.f();
    obj.f();
}
jogojapan
  • 68,383
  • 11
  • 101
  • 131
uss
  • 1,271
  • 1
  • 13
  • 29
  • 5
    Because `B::f(int=0)` is not in the override chain of `A::f()`; it is independent of either `A::f()` or `C::f()`. The signatures are different. Is your question more of why did the compiler choose `B::f(int=0)` rather than `C::f()` (through `A::f()`) since they would be called the same way? – WhozCraig Feb 18 '13 at 06:11
  • 1
    Related: http://stackoverflow.com/questions/3533589/can-virtual-functions-have-default-parameters – jogojapan Feb 18 '13 at 06:46

1 Answers1

6

The f(int x = 0) method in the B struct does not share a signature with either the A nor C struct's f() methods.

Aesthete
  • 18,622
  • 6
  • 36
  • 45
  • 4
    +1. Because B::f(int=0) and `A::f()` are in fact, different, there are two possible candidates that can be called. Therefore, this call undergoes **overload resolution** rather than virtual polymorphism. The best fitting candidate is chosen, and in this case, it is `B::f(int=0)`. I can search the standard for the exact rule(s) of resolution that trip(s) this if needed, but that is ultimately the fundamental reason why `C::f()` is not called. – WhozCraig Feb 18 '13 at 06:26
  • I'm sure many people, including myself would be interested in that document if you linked it. – Aesthete Feb 18 '13 at 06:40
  • It's always good to add the relevant Standard quote if it's not too much trouble. – jogojapan Feb 18 '13 at 06:40
  • I'll do some surfing in the standard and see what bubbles up. Overload resolution is covered in C++ § 13, with 13.2 covering Declaration Matching and 13.3 covering Resolution (my money is on 13.3.2 Viable Functions, and 13.3.3 Best Viable Function, but rarely is the standard so straight forward). – WhozCraig Feb 18 '13 at 06:47