using in class

1 #include <iostream>
2
3 using namespace std;
4
5 class B {
6 public:
7 void f(char) {
8 cout<<"In B::f()"<<endl;
9 }
10 void g(char) {
11 cout<<"In B::g()"<<endl;
12 }
13 };
14
15 class D:B {
16 public:
17 //using B::f;
18 //using B::g;
19 void f(int) {
20 cout<<"In D::f()"<<endl;
21 f('c');
22 }
23 void g(int) {
24 cout<<"In D::g()"<<endl;
25 g('c');
26 }
27 };
28
29 int main() {
30 D ob;
31 ob.f(1);
32 ob.g('a');
33 return 0;
34 }

The above code runs in an infinite loop. By uncommenting line no. 17 & 18, why there is no infinite loop ???
When class D is derived from class B and both class have same function names but with different signatures (arguments)

then this kind of inheritance design is not call 'function overridding / over loading' ... !! which i believe you are trying to achieve .. instead this concept is called 'function hiding'..

So when you are intended to call g('a') it does not call g() in B class .. rather the function in D class gets executed with 'char' get casted to 'int' type, and since g() has become a recursive function hence the control keep jumping to g(int) in D class.

when you uncomment the 17th and 18th line , the keyword 'using' explicitly define base methods in derived..
another way to do this is write __super::method_name() in derived class instead of using as many compilers does not support 'using'.
__super is define in STL.
Topic archived. No new replies allowed.