0

My book covered superficially many test topics from the Object-Oriented domain and I need some explanation and a hint which book does cover such topics.

There's a test question:

#include <iostream>

class A {
public:
    virtual void f(int n=2) {// takes the argument value from here
        std::cout << n+1 << " in A";
    }
};
class B : public A {
private:
    virtual void f(int n=3) {
        std::cout << n - 1 << " in B";// this class is used
    }
};

int main() {
    A* p = new B;
    p->f();
}

Output: 1 in B, that is the argument from A fed into B.

I understand why the object of the class B is created. I don't understand why is the value of 2 taken as the argument. I also checked if the class A's value would be taken if the variable's name were changed -- it is still used.

Any literature to read about this or educational videos on such OOP topics is welcome.

Mykola Tetiuk
  • 153
  • 1
  • 13
  • 2
    Because `p` is `A *`, rather than `B *`. Virtual-ness only affects which function is selected, not its arguments. – HolyBlackCat Jun 16 '21 at 05:47
  • 1
    If you got the answer you need, please Accept the answer, it will give you reputation and flag the question as resolved. If the answer is laking, feel free to ask for clarification – Martin Morterol Jun 17 '21 at 06:35

1 Answers1

2

You have more info here : Can virtual functions have default parameters?

The idea is "the static type of p is A so it will use the default value of A::f"

IMHO, it's a detail and probably not what you should be focusing if you are learning OOP, but it's great you did see it.

Martin Morterol
  • 2,560
  • 1
  • 10
  • 15