Open In App

Calling a non-member function inside a class in C++

Member Function: It is a function that can be declared as members of a class. It is usually declared inside the class definition and works on data members of the same class. It can have access to private, public, and protected data members of the same class. This function is declared as shown below:




// Given Class
class memberdemo {
private:
    {
    public:
        {
            void check();
        }
 
        // Member Function
        trial::void check();
    }
}

Non-member Function: The function which is declared outside the class is known as the non-member function of that class. Below is the difference between the two:



Program 1:




// C++ to illustrate the above concepts
#include <iostream>
using namespace std;
 
class A {
    int a;
 
public:
    // Member function
    void memberfn(int x)
    {
        a = x;
        cout << "Member function inside"
             << " class declared\n";
    }
 
    // Member function but definition
    // outside the class
    void memberfn2();
};
 
// Member function declared with
// scope resolution operator
void A::memberfn2()
{
    cout << "Member function but declared "
         << " outside the class\n";
}
 
// Non-member function
void nonmemberfn()
{
    cout << "Non-member function\n";
}
 
// Driver Code
int main()
{
    // Object of class A
    A obj;
 
    // Calling Member Function
    obj.memberfn(5);
    obj.memberfn2();
 
    // Calling Non-Member Function
    nonmemberfn();
 
    return 0;
}

Output:

Member function inside class declared
Member function but declared  outside the class
Non-member function

Explanation: From the above program, there are three types of cases:

Now, the question here arises whether it is possible to call a non-member function inside a member function in a program or not. The answer is YES. Below is the program to illustrate how to call a non-member function inside a member function:

Program 2:




// C++ program to illustrate the
// above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the factorial
// of the number N
int fact(int n)
{
    if (n == 0 || n == 1)
        return 1;
    else
        return n * fact(n - 1);
}
 
// Class Examples
class example {
    int x;
 
public:
    void set(int x) { this->x = x; }
 
    // Calling the non-member function
    // inside the function of class
    int find() { return fact(x); }
};
 
// Driver Code
int main()
{
    // Object of the class
    example obj;
 
    obj.set(5);
 
    // Calling the member function
    cout << obj.find();
 
    return 0;
}

Output:
120

Explanation: A non-member function can be called inside a member function but the condition is that the non-member function must be declared before the member function. In the above example, the same approach is followed and it becomes possible to invoke a non-member function thus the answer is the factorial of 5 i.e. 120.


Article Tags :