0

The following code compiles without any warning or error:

#include <iostream>
using namespace std;
class demo_class
{
    int x;
    float y;
    public:
    void fun(void);
};
void fun2(void)
{
    cout<<"i am fun2\n";
}
void demo_class::fun(void)
{
    cout<<"i am fun\n";
    cout<<"i can call fun2\n";
    fun2();
}
int main()
{
    demo_class ob1;
    ob1.fun();
    return 0;
}

I am not understanding that as the scope of fun function is only in demo_class then how can it call fun2 function, should not it show error as the access of fun function only within the demo_class?

Mat
  • 188,820
  • 38
  • 367
  • 383
play store
  • 383
  • 1
  • 5

2 Answers2

2

Name lookup would try to examine all the possible scopes, until it finds at least one at any scope, then the name lookup stops.

In this case, the name fun2 can't be found at class scope, then the further scope, i.e. globle scope is examined and ::fun2 is found.

songyuanyao
  • 147,421
  • 15
  • 261
  • 354
1

There is no reason to disallow calling a free function from within a member function. If this was the case classes would be rather useless (they would be a way to prevent code reuse instead of supporting it).

As mentioned in a comment, in cout<<"i am fun2\n"; you are calling a non-member function and calling fun is not much different from that.

Further, with a grain of salt your example is not much different from

#include <iostream>
using namespace std;
class demo_class
{

};
void fun2(void)
{
    cout<<"i am fun2\n";
}
void fun3(demo_class& dc)
{
    cout<<"i am fun\n";
    cout<<"i can call fun2\n";
    fun2();
}
int main()
{
    demo_class ob1;
    fun3(ob1);
    return 0;
}

A member function can always be transformed into a free function. If fun would access private members we would have to declare it as friend to make the above work, but otherwise no problem here.

You can also do the reverse and call member functions in free functions as in

 struct foo {
     void bar(){}
 };

 void func(foo& f) { 
      f.bar();
 }

 int main() {
     foo f;
     func(f);
 }
463035818_is_not_a_number
  • 64,173
  • 8
  • 58
  • 126