×

C++ Member Functions


What are Member Functions ?

Member functions are the functions which are applied to the dataMembers of the class. Member functions can be declared inside a class or outside a class.

Member Functions defined inside a class

Example :-

#include <iostream>
using namespace std;
class Game
{
public:
  int i;                   //data variable
  void  display(string str)

  { 
   cout<<str<<"\n";
  }

}; // Class ends here


int main()
{
 Game sankeObject;                     // Creatig Game class's object
 sankeObject.display("Sanke Game");    //Calling member function using class object

 Game pacmanObject;
 pacmanObject.display("Pacman Game");
}

Output :-

Save file as Game.cpp 
Open terminal
Access to the directory where Game.cpp is stored.

In terminal , then write this
g++ Game.cpp 
Once the file is compiled successfully, write this in terminal
./a.out

Snack Game
Pacman Game

Firstly main() function is called . Then it creates first instance of Game class named sankeObject. The display Method is called where it prints the passed the string using parameter str. Then it creates second object of Game class named pacmanObject. Then it calls a display function again with different string "Pacman Game."

Member Function defined outside the class

You can define the member functions outside the class using scope resolution operator written as two colons ::

Example :-

#include <iostream>
using namespace std;
class Game
{
public:
  int i;                       // data member
  void  display(string str) ;  // Member Function Declaration

}; // Class ends here

 void Game :: display(string str)         //Member Function Defination
  { 
   cout<<str<<"\n";
  }

int main()
{
 Game sankeObject;                     // Creatig Game class's object
 sankeObject.display("Sanke Game");    //Calling member function using class object

 Game pacmanObject;
 pacmanObject.display("Pacman Game");
}