+ 1

multi-level Inheritance

#include <iostream> using namespace std; class A {}; class B : public A {}; class C : public B {}; void method(A a) {cout<<'a';} void method(B b) {cout<<'b';} int main() { C c; method (c); return 0; } // outputs b To call a function, we need to pass the the function name and required parameters... Why is method (B b) executed when it does NOT have matching parameters as method (c)... ======================= Question 1: Why and how is method (c) of class C able to call method (B b) of class B and unable to call method (A a) of class A? Is it that we can only call one level above in a multi-level inheritance situation? ======================= Question 2: If there was a global 'void method(C c) {cout<<'c';}', why would method (B b) no longer be called?

5th Aug 2020, 8:00 AM
Solus
Solus - avatar
1 ответ
+ 2
Let's not call them methods, but functions! Q1) C will be upcast to B simply because B is the next step up in the class hierarchy. You can still call the other function, by casting explicitly: `method((A)c);` Q2) That is correct, no cast is necessary so that's the function that will be called. But again with an explicit cast you can call all 3.
5th Aug 2020, 8:50 AM
Schindlabua
Schindlabua - avatar