Member functions can also be overloaded. Overload resolution for member functions is very similar to overload resolution for nonmember functions. The processe composed of the same three steps:
There are some minor differences in how candidate functions and viable functions are selected for calls to member functions. We will examine these differences in this section.
mf() in the scope of class myClass.
myClass mc;
myClass* pmc;
mc.mf( arg );
pmc->mf( arg );
myClass::mf( arg );
mf() exists in myClass, the set of candidate functions is empty. (Actually, functions in base classes may then be considered.) #include <iostream>
struct myClass {
static void mf(int){ std::cout << "A\n"; };
void mf(char){ std::cout << "B\n"; };
};
int main() {
char c = 1;
myClass::mf(c);
return 0;
}
mf(double) cannot be called, it is excluded from the set of viable functions. The only viable function for the call is the const member function mf(int) , which is selected as the best viable function for the call.
#include <iostream>
struct myClass {
static void mf(int*){ std::cout << "A\n"; };
void mf(double){ std::cout << "B\n"; };
void mf(int) const{ std::cout << "C\n"; };
};
int main() {
const myClass mc;
mc.mf(1.2); // C
return 0;
}
mf(int). For this reason it is always valid to call a static member function for a const object using the dot or arrow operator.
#include <iostream>
class Student {
public:
Student(int id) : m_id(id) {}
static void foo() { std::cout << "Called static function\n"; }
private:
int m_id;
};
int main() {
Student s(1);
s.foo();
return 0;
}