c sharp Logo

Class Methods


A class method in C++ is a function that is defined within a class and can be used to operate on the class's data members. Class methods can be used to access and modify the data members of the class, as well as to perform other tasks, such as printing the state of the object or performing calculations.

Example

The following code shows a simple class named Rectangle with a class method named CalculateArea():

class Rectangle {

public:

  Rectangle(int width, int height) {

    this->width = width;

    this->height = height;

  }

 

  int CalculateArea() {

    return width * height;

  }

 

private:

  int width;

  int height;

};

 

The CalculateArea() method calculates the area of the rectangle and returns the result.

To use the CalculateArea() method, you would first create a Rectangle object and then call the method on the object. For example:

Rectangle rectangle(10, 5);

 

int area = rectangle.CalculateArea();

 

This code will calculate the area of the rectangle and store the result in the variable area.

Types of class methods

There are two types of class methods:

  • Public methods: Public methods can be accessed from anywhere in the program.
  • Private methods: Private methods can only be accessed from within the class itself.

Private methods are typically used to implement internal functionality of the class. For example, the Rectangle class might have a private method to calculate the perimeter of the rectangle. This method would be used by the CalculateArea() method to calculate the area of the rectangle, but it would not be accessible to users of the Rectangle class directly.

Conclusion

Class methods are a powerful feature of C++ that can be used to write more modular, reusable, and flexible code. By understanding how to use class methods, you can write better C++ code.