DEFINITION 12: METHOD - PRATMG/2143-OOP-Tamang GitHub Wiki

In OOP's Concepts, a method is a procedure or function. A function, on the other hand, is a collection of reusable code that can be used anywhere in the program. This reduces the need to write the same code over and over. It helps programmers in the writing modular code.

methods:

  • A method also works the same as that of function.
  • A method is defined inside a class.
  • A method can be private, public, or protected.
  • The method is invoked by its reference/object only. For Example: If class has obj as an object name, then the method is called by:
obj.method();
  • A method is able to operate on data that is contained within the class
  • Each object has itโ€™s own method which is present in the class.
// C++ program to illustrate methods
// in class
#include "bits/stdc++.h"
using namespace std;

// Class GfG
class GfG {
private:
	string str = "Welcome to GfG!";

public:
	// Method to access the private
	// member of class
	void printString()
	{

		// Print string str
		cout << str << '\n';
	}
};

// Driver Code
int main()
{

	// Create object of class GfG
	GfG g;

	// Accessing private member of
	// class GfG using public methods
	g.printString();

	return 0;
}

Reference: