Methods
C++ Methods
In object-oriented programming (OOP), a method is a function that is associated with an object. It operates on the object's data and is defined within a class. In C++, methods are commonly referred to as member functions because they are members of a class. Here's an overview of methods in C++:
Class Definition with Methods:
#include <iostream>
// Class definition
class Calculator {
public:
// Member function declaration
int add(int a, int b);
// Another member function declaration
void displayResult(int result);
};
// Member function definition
int Calculator::add(int a, int b) {
return a + b;
}
// Another member function definition
void Calculator::displayResult(int result) {
std::cout << "Result: " << result << std::endl;
}
In this example, a class named Calculator
is defined with two member functions: add
and displayResult
. These functions are declared within the class and defined outside of it.
Creating Objects and Calling Methods:
int main() {
// Create an object of the Calculator class
Calculator myCalculator;
// Call the add method
int sum = myCalculator.add(3, 4);
// Call the displayResult method
myCalculator.displayResult(sum);
return 0;
}
In the main
function, an object myCalculator
of the Calculator
class is created. The add
and displayResult
methods are then called on this object.
Access Control:
In the example above, the public
keyword is used to specify that the member functions are accessible from outside the class. There are also private
and protected
access specifiers in C++.
class MyClass {
private:
// Private members
public:
// Public members
protected:
// Protected members
};
Member Initialization List:
class Rectangle {
private:
int length;
int width;
public:
// Constructor with member initialization list
Rectangle(int l, int w) : length(l), width(w) {}
// Other member functions
};
Static Member Functions:
class MathUtility {
public:
// Static member function
static int add(int a, int b);
};
// Definition of the static member function
int MathUtility::add(int a, int b) {
return a + b;
}
int main() {
// Call the static member function
int result = MathUtility::add(3, 4);
return 0;
}
Const Member Functions:
class Circle {
private:
double radius;
public:
// Constructor
Circle(double r) : radius(r) {}
// Const member function
double getRadius() const {
return radius;
}
};
Understanding how to define and use methods is fundamental to working with classes and objects in C++. Methods encapsulate the behavior of objects and contribute to the overall structure and modularity of your code.