banner
cells

cells

为美好的世界献上 code

Q160

Q160#

#include <iostream>

struct A {
    virtual void foo(int a = 1) {
        std::cout << "A" << a;
    }
};

class B : A {
    virtual void foo(int a = 2) {
        std::cout << "B" << a;
    }
};

int main() {
    A *b = new B;
    b->foo();
    return 0;
}

Explain#

In the first line of main, we create a new B object, with an A pointer a pointing to it.

On the next line, we call b->foo(), where b has the static type A, and the dynamic type B. Since foo() is virtual, the dynamic type of b is used to ensure B::foo() gets called rather than A::foo().

A virtual function call uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides.

So B::foo() is called, but with the default argument from A::foo()

Answer#

click to see answer B1
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.