Having the following hierarchy with virtual functions and default parameters, what will the following program print out to the console?
#include <iostream>
using namespace std;

struct A
{
    virtual void print(int x = 0) const {
        cout << x;        
    }
};

struct B: public A
{
    virtual void print(int x = 3) const {
        A::print(x);
    }
};

int main()
{
    A* pa = new A; pa->print();
    A* pb = new B; pb->print();
    
    A a; a.print();
    B b; b.print();

    return 0;
}
Explanation
The default value of the parameter has static binding, i.e. determined at compile time. In this case, the objects pa and pb are recognized by the compiler as objects of type A*, therefore, when the print() method is called, the compiler sets the default parameter 0, corresponding to type A. At the same time, the compiler treats objects a and b as objects of types A and B; therefore, when the print() method is called, it sets the default values ​​to 0 and 3, respectively.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Cosmo
Sign Up Now
or Subscribe for future quizzes