0

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 = bis 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)
XDProgrammer
  • 853
  • 2
  • 14
  • 31
  • Interesting. It would seem to be getting the argument value from the declared class type and then calling the function of the runtime class type. I'm sure some more skilled C++ junkie than I can come along and explain why that's the case. – Silvio Mayolo Jul 29 '15 at 21:41
  • @SilvioMayolo yes, it definitelly gets the argument from the base class. But I am really puzzled why, as well as the private method being called directly outside the class.. – XDProgrammer Jul 29 '15 at 21:46
  • Closing - the questions aren't really the same, but the accepted answer to the other question covers this very well. – aschepler Jul 29 '15 at 21:53
  • @aschepler Hi, I can see similarities but how bout the private in class C? – XDProgrammer Jul 29 '15 at 21:57
  • Private functions can still override, and get called via a base class reference or pointer. – aschepler Jul 29 '15 at 22:05

0 Answers0