A member function of class in c++ are function that belong to the class.

There are two ways to define the Member function of class in c++

  • Inside class definition.
  • Outside class definition.
member function in cpp

Inside class definition of member function.

NOTE: You access Methods just like you access attributes; by creating an object of the class and using the dot syntax (.):

 class classname
 {
    public:
		 
	inside function()
	{
             .
             .
             .
	}
 };

 main function()
 {
   classname object;
   
   object . insidefunction(); //call the method
 
 }

In the following example, We define a function inside the class and we name it “xyz”.

Example

#include<iostream.h>
#include<conio.h>
class xyz // The Class
{
    public:   // Access Specifier

	void getdata() // getdata function defined inside the class.
	{
		cout << "Hello World!";
	}
};

void main()
{
   xyz x1  // create an object of xyz class.
   x1.getdata();  // Call the method
}

output

Hello World!

Outside class definition.

NOTE: To define a function outside the class definition, you have to declare it inside the class
and then define it outside of the class.

NOTE: This is done by specifying the name of the class followed the scope resolution :: operator, followed by the name of the function.

 class classname
 {
      public:
		 
	declaration function();
		 
 };

 // used declaration function outside class.
 return type classname :: declaration function()
 {
		.		.
		.
 }
  

 main function()
 {
   classname object;
   
   object . insidefunction(); //call the method
 
 }

In the following example, We define a function outside class and we name it “xyz”.

Example

#include<iostream.h>
#include<conio.h>

class xyz // The Class
{
  public:   // Access Specifier

   void getdata(); // getdata function declaration
};

// getdata function definition outside the class

void xyz :: getdata()
{
   cout << "Hello World!";
}

void main()
{
   xyz x1  // create an object of xyz class.
  
   x1.getdata();  // Call the method

  getch();
}

Output

Hello World!