4

Can somebody please explain why is the output of the following code is B:2 ? How does the variable x get the value of num when there is no call to A::print(int)

#include <iostream>

class A
{
  public:
    void virtual print(int num = 2) {
         std::cout << "A:" << num << std::endl;
    }
};

class B : public A
{
  public:
    void virtual print(int x = 22) {
        std::cout << "B:" << x << std::endl;
    }
};

int main()
{
    A *a = new B;
    a->print();
    delete a;
    return 1;
}
RoiHatam
  • 876
  • 10
  • 19
  • 5
    I think that the point of the question is rather about the default parameters combined with virtual method calls. The answer should be here: https://stackoverflow.com/questions/3533589/can-virtual-functions-have-default-parameters – Ardavel Jun 29 '17 at 22:22
  • 6
    Default parameters are not selected by the virtual function mechanism. –  Jun 29 '17 at 22:23
  • this is one of the reasons why default params are a bad idea – pm100 Jun 29 '17 at 22:24
  • @pm100 I almost said that in my comment, but of course default template parameters are very useful. –  Jun 29 '17 at 22:25

0 Answers0