Tuesday, 9 April 2019

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

Scribe to Youtube Channel

Advertisement

Find Us On Facebook

C Programming

More

C++ Tutorial

More

Java Tutorial

More

software engineering

More

MS Office

More

Database Management

More
Top