This is the part of C++ that things looks confusing to me. Consider this basic of example of inheritance and polymorphism. Each class below has virtual functions and called in the main function, but the output puzzles me a bit.
First, I understand that A& r1 = b
is a reference to the B object that was created before, and it should call the test function in B because both are virtual. From what I've learned the most-derived/latest function will be called.
Yes, it calls the lastest function but what I am concerned is the argument, in the output says 10
, but the default argument in test function in class B is 50
. Same goes for A& r2 = c
, the test function in C has no default argument but gets the argument in test function from class B instead.
Also the test function in C are private, Isn't that if private you can only call them inside the class?
I highly appreciate it if someone could enlighten me in this part. Thank you
#include <iostream>
using namespace std;
class A {
public:
virtual void test(int n = 10)
{
cout << "class A test(" << n << ")" << endl;
}
};
class B: public A {
public:
virtual void test(int n = 50)
{
cout << "class B test(" << n << ")" << endl;
}
};
class C: public B {
public:
//no public
private:
virtual void test()
{
cout << "class C test()" << endl;
}
virtual void test(int n)
{
cout << "class C test(" << n << ")" << endl;
}
};
int main () {
A a;
B b;
C c;
A& r1 = b;
A& r2 = c;
B& r3 = c;
r1.test();
r2.test();
r3.test();
}
OUTPUT
class B test(10)
class C test(10)
class C test(50)