0

I'm so confused, why I can't access void func(int i), anybody can help me? Of course this is just a demo to help your understand my question easily. Its real code is huge, I want the member functions in Base and Child both available.

The output always is **

double
2

**

        struct base
        {
            void func(int i)
            {
                cout << "int" << endl;
                cout << i << endl;
            }
        };

        struct child : base
        {
            void func(double d)
            {
                cout << "double" << endl;
                cout << d << endl;
            }
        };

        child c;
        c.func((int)2);
Triumphant
  • 948
  • 1
  • 11
  • 28

2 Answers2

3

Because child::func hides base::func.

You need to either make it visible in the derived class by bringing the name in scope:

struct child : base
{
    using base::func;
     void func(double d)
     {
         cout << "double" << endl;
         cout << d << endl;
     }
};

or call the base version explicitly by qualifying the name at the call site:

c.base::func(2);
jrok
  • 54,456
  • 9
  • 109
  • 141
  • They receive different parameters. They should operate as if overloaded (int variables go to base / double variables to go child). Not that I believe that passing a constant will produce any reliable results. – ciphermagi Mar 03 '14 at 10:18
  • @ciphermagi There's a good reason behind name hiding - [see this answer](http://stackoverflow.com/questions/1628768/why-does-an-overridden-function-in-the-derived-class-hide-other-overloads-of-the). – jrok Mar 03 '14 at 10:37
1

The implicit conversion from int to double is masking the actual problem. If you change your base class func parameter type from int to string:

struct base
{
    void func(string i)
    {
        cout << "string" << endl;
        cout << i << endl;
    }
};

Then you'd receive the following error to make it clearer:

func.cpp: In function `int main()':
func.cpp:27: error: no matching function for call to `child::func(const char[13])'
func.cpp:17: note: candidates are: void child::func(double)

Where you can see it only has visibility of child::func not base::func

Simon Bosley
  • 1,114
  • 3
  • 18
  • 41
  • There's an interesting post here on the [automatic conversion of method parameters](http://stackoverflow.com/questions/175689/can-you-use-keyword-explicit-to-prevent-automatic-conversion-of-method-parameter) – Simon Bosley Mar 03 '14 at 10:35