C++ - Methods

In C++, class methods are member functions defined within a class. They are used to perform actions or operations on the data members of the class. Class methods can access and modify the private data members of the class, as well as interact with other member functions.

Defining Class Methods:

Class methods are defined within the class definition using the function syntax. They can be declared as public, private, or protected, depending on their intended accessibility. Public methods can be accessed from outside the class, while private methods are only accessible within the class itself. Here's an example:

class Rectangle {
private:
    double length;
    double width;
public:
    void setDimensions(double len, double wid) {
        length = len;
        width = wid;
    }
    double getArea() {
        return length * width;
    }
};

In this example, the setDimensions() method is a public method that takes two parameters (len and wid). It sets the values of the private data members length and width. The getArea() method is also a public method that calculates and returns the area of the rectangle.

Method Parameters:

Method parameters are variables defined within the parentheses after the method name. They allow you to pass values or objects to the method for performing specific operations. Parameters enable the method to work with different values each time it is called. Here's an example that demonstrates method parameters:

class Calculator {
public:
    int addNumbers(int num1, int num2) {
        return num1 + num2;
    }
};

In this example, the addNumbers() method takes two parameters (num1 and num2) of type int. It adds the values of num1 and num2 and returns the result.

Using Class Methods:

Once a class method is defined, it can be invoked on an object of the class using the dot (.) operator. The method can access the object's data members and perform operations based on the defined behaviors. Here's an example:

int main() {
    Rectangle rectangle;
    rectangle.setDimensions(5.0, 3.0);
    double area = rectangle.getArea();
    return 0;
}

In this example, an object of the Rectangle class is created using the rectangle variable. The setDimensions() method is called on the rectangle object, passing the values 5.0 and 3.0 as the arguments. This sets the dimensions of the rectangle. Then, the getArea() method is called to calculate and store the area of the rectangle in the area variable.