c++scope-resolution-operator

Why can't I call showA() using A's object?


Why are we able to call the showA() method without object? But if I use void A::showA(A& x) in the method definition then I have to call it using A's object, why?

#include <iostream> 

class A { 

public:
    int a;
    A() { a = 0; } 


     void showA(A&); 
}; 

void showA(A& x) 
{ 

    std::cout << "A::a=" << x.a; 
} 

int main() 
{ 
    A a; 
    showA(a); 
    return 0; 
}

Solution

  • Why are we able to call the showA() method without object?

    You don't call the member function A::showA, but instead the free function showA. In fact, the member function A::showA(A&) is declared, but never defined, only the free function showA(A&) has a definition.

    If you want to call A::showA, you need a definition;

    void A::showA(A& x) { /* ... */ }
    //   ^^^ this makes it a member function definition
    

    and then call it as

    A a;
    
    a.showA(a);
    

    (Note that it doesn't make much sense to pass the a instance to A::showA invoked on the identical a instance, but that's another issue).