Cpp Tutorial: Different types of Member Functions in C++

Below are different types of member functions available in C++

1. Simple member functions
2. Static member functions
3. Const member functions
4. Inline member functions
5. Friend functions

1. Simple member functions:

The function defined inside a class without any kind of keyword delared are called as simple member functions.

Example:

#include <iostream>  

// for more tutorial in C++ visit www.prodevelopertutorial.com
using namespace std;  
  
class MyClass 
{ 
    int *ptr; 
public: 
    void myfun();
}; 

void MyClass::myfun()
{
    
}

int main() 
{ 
    MyClass obj;
    return 0; 
}

2. Static member functions

“static” is the keyword used to make a member function static member function.

They are class based instead of object based.

You can call a static function with class name along with scope resolution operator “::”.

A static function can only access static data member.

Example:

#include <iostream>  

// for more tutorial in C++ visit www.prodevelopertutorial.com
using namespace std;  
  
class MyClass 
{ 

public: 
    static void myfun();
}; 

void MyClass::myfun()
{
    cout<<"Static function"<<endl;   
}

int main() 
{ 
    MyClass::myfun();
    return 0; 
}

3. Const member functions

“const” keyword is used to create a const member function.

There are times, where we dont want a member function to change the values of data members.

Hence we use “const” member function.

If the data member is made as mutable, then we can modify the data member in const member function.

Example:

#include <iostream>  

// for more tutorial in C++ visit www.prodevelopertutorial.com
using namespace std;  

class MyClass 
{ 
    int i; 
    mutable int j;
public: 
     void myfun() const;
}; 

void MyClass::myfun() const
{
    //i ++; // you will get an error
    j ++;   
}

int main() 
{ 
    MyClass obj;
    obj.myfun();
    return 0; 
}

4. Inline member functions

If the member function defind inside a class, it will be inline member function.

If you define a member function outside the class, you can make it inline using “inline” keyword.

Example:

#include <iostream>  

// for more tutorial in C++ visit www.prodevelopertutorial.com
using namespace std;  

class MyClass 
{ 
    int j;
public: 
     void myfun();
}; 

void inline MyClass::myfun() 
{
    j ++;   
}

int main() 
{ 
    MyClass obj;
    obj.myfun();
    return 0; 
}

5. Friend functions

Friend functions are not class member function.
The friend functions have access to private data members of the class.

Example:

#include <iostream>  

// for more tutorial in C++ visit www.prodevelopertutorial.com
using namespace std;  

class MyClass 
{ 
    int j;
public: 
    friend void myfun();
}; 

void myfun() 
{
    MyClass obj;
    
    obj.j ++;   
}

int main() 
{ 
    myfun();
    return 0; 
}
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *