A method is a procedure or function in OOPs Concepts. Whereas, a function is a group of reusable code which can be used anywhere in the program. This helps the need for writing the same code again and again. It helps programmers in writing modular codes.
Methods:
- A method also works the same as that of function.
- A method is defined inside a class. For Example: main() in Java
- 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.
Functions:
- A function is a block of statements that takes specific input, does some computations, and finally produces the output.
- A function is defined independently. For Example: main() in C++
- By default a function is public.
- It can be accessed anywhere in the entire program.
- It is called by its name itself.
- It has the ability to return values if needed.
- If a function is defined, it will be the same for every object that has been created.
Below is the program to illustrate functions and methods in C++:
Program 1:
#include "bits/stdc++.h"
using namespace std;
void printElement( int arr[], int N)
{
for ( int i = 0; i < N; i++) {
cout << arr[i] << ' ' ;
}
}
int main()
{
int arr[] = { 13, 15, 66, 66, 37,
8, 8, 11, 52 };
int N = sizeof (arr) / sizeof (arr[0]);
printElement(arr, N);
return 0;
}
|
Output:
13 15 66 66 37 8 8 11 52
Program 2:
#include "bits/stdc++.h"
using namespace std;
class GfG {
private :
string str = "Welcome to GfG!" ;
public :
void printString()
{
cout << str << '\n' ;
}
};
int main()
{
GfG g;
g.printString();
return 0;
}
|
Program 3:
#include <iostream>
using namespace std;
string offering( bool a)
{
if (a) {
return "Apple." ;
}
else {
return "Chocolate." ;
}
}
class GFG {
public :
void guest( bool op)
{
if (op == true ) {
cout << "Yes, I want fruit!\n" ;
}
else {
cout << "No, Thanks!\n" ;
}
}
};
int main()
{
bool n = true ;
cout << "Will you eat fruit? " ;
GFG obj;
obj.guest(n);
if (n == true ) {
cout << "Give an " + offering(n);
}
else {
cout << "Give a " + offering(n);
}
return 0;
}
|
Output:
Will you eat fruit? Yes, I want fruit!
Give an Apple.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Jun, 2020
Like Article
Save Article