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 {

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

    return 0;
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.

Слідкуй за CodeGalaxy

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

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