Monday, 6 April 2020

Difference between a member and a non-member function in C++?

There are two major differences.

1.A non-member function always appears outside of a class.

The member function can appear outside of the class body (for instance, in the implementation file). But, when you do this, the member function must be qualified by the name of its class. This is to identify that that function is a member of a particular class.


For instance, if you took myarray class and wanted to define the implementation of a new member function called myfunction outside the body of the class.

You would write:

int myarray::myfunction(int a, int b)
{
 ...//details of this implementation
    //note: you need the protype of myfunction in the body of myarray
}



The myarray:: specifies that the myfunction belongs to the myarray class.

By contrast, a non-member function has no need to be qualified. It does not belong to a class. In the implementation file, I could write my non-member function as:
    int myfunction (int a, int b)
    {
     ..//details of this implementation
    }


2. Another difference between member functions and non-member functions is how they are called (or invoked) in the main routine.
    int main()
     {  int i;  
    myarray a; //declare a myarray object  
    i=myfunction(3,2); //invoking the non-member function  
    i=a.myfunction(3,2); //invoking the member function 
    } 


The member function is called using object and dot operator, whereas the non-member function cannot.

 Reference:

https://www.quora.com/What-is-the-difference-between-a-member-and-a-non-member-function-in-C
 

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.

Find Us On Facebook

python tutorial

More

C Programming

More

Java Tutorial

More

Data Structures

More

MS Office

More

Database Management

More
Top