Home > Net >  c member function hides global function
c member function hides global function

Time:09-03

This code snippet doesn't compile:

struct M {
    int i;
    int j;
};

void f(M& m) {
    m.i  ;
}

struct N {
    M m;
    void f(int i) {
        f(m); // compilation error
    }
};

clang says : No viable conversion from 'M' to 'int' Seems my member function hides global function.

I changed the error line into ::f(m) to help name resolution, but still fails. Does it mean that in c member function, cannot call global overload function with same name but different parameter list?

How to fix this? Thanks!

CodePudding user response:

c member function hides global function

This has nothing to with hiding.

The problem is that the call expression f(m) inside the member function is equivalent to writing:

this->f(m); //this is equivalent to just writing f(m)

As you can see above, writing f(m) or this->f(m) inside the member function is equivalent and so the global f(M&) is not even considered and hence cannot be used.

To solve this, use the scope operator :: to call the global function f as shown below:

struct N {
    M m;
    void f(int i) {
//------vv---------->use the scope operator :: to call the global version
        ::f(m); 
    }
};

Working Demo

  • Related