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.

2
  • 2
    Because p is A *, rather than B *. Virtual-ness only affects which function is selected, not its arguments. Commented Jun 16, 2021 at 5: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 Commented Jun 17, 2021 at 6:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.