What will be printed out as a result of the following code execution?
#include "iostream"
class A
{
public:
    virtual int mathFunc(int n = 1) {return n+n;}
};

class B: public A
{
public:
    int mathFunc(int n = 2) {return n*n;}
};

int main()
{
    A a, *pa;
    B b;
    pa = &b;

    std::cout << a.mathFunc(3) 
              << pa->mathFunc(-1)
              << pa->mathFunc()
              << b.mathFunc();
}
Explanation
Here: pa->mathFunc() class B method will be called, but default parameters will be taken from the base class.

The compiler strictly follows the language standard, which specifies to substitute default parameter values into the function call code based on the static type of the pointer used to call the virtual function. In this case, the static pointer type *pa is class A, i.e. the default parameters will be taken from class A.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести