function overloading

i am having a hard time understanding overloading of functions in this code..i am not able to understand why isnt the compiler able to detect the same declaration of fun()....further i didnt even understand line9 where a constructor is inherited....how is it inherited???plz help me in understanding this...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
using namespace std;
 
class Test
{
protected:
    int x;
public:
    Test (int i):x(i) { }
    void fun() const
    {
        cout << "fun() const called " << endl;
    }
    void fun()
    {
        cout << "fun() called " << endl;
    }
};
 
int main()
{
    Test t1 (10);
    const Test t2 (20);
    t1.fun();
    t2.fun();
    return 0;
}
Non-static member functions have one more implicit parameter of type either SomeClass * or const SomeClass * depending on whether the trailing const qualifier is present.
So in fact the definitions

1
2
3
4
5
6
7
8
    void fun() const
    {
        cout << "fun() const called " << endl;
    }
    void fun()
    {
        cout << "fun() called " << endl;
    }

can be considered as equivalent to the following definitions

1
2
3
4
5
6
7
8
    void fun( const Test *this ) 
    {
        cout << "fun() const called " << endl;
    }
    void fun( Test *this )
    {
        cout << "fun() called " << endl;
    }


So when a const object is used the compiler selects the first function. Otherwise it selects the second function.

As for "inherited constructor" then there is no any inherited constructor.
Last edited on
Topic archived. No new replies allowed.