Class methods

Class methods

Class methods

In C++, a class method is a function that is defined inside a class and operates on objects of that class. Class methods are also known as member functions. They can access the data members and other member functions of the class.

Here’s an example of a class with a method:

				
					class Rectangle {

public:

  int width, height;

  int area() {

    return width * height;

  }

};Bottom of Form

​
				
			

In this example, the Rectangle class has two data members (width and height) and a method called area. The area method calculates the area of the rectangle by multiplying its width and height.

To call the area method on a Rectangle object, you would use the dot (.) operator:

				
					Rectangle myRect;

myRect.width = 5;

myRect.height = 10;

int myArea = myRect.area(); // returns 50
​
				
			

In C++, a class method is a function that is defined inside a class and operates on objects of that class. Class methods are also known as member functions. They can access the data members and other member functions of the class.

Here’s an example of a class with a method:

				
					class Rectangle { public: int width, height; int area() { return width * height; } };

​
				
			

In this example, the Rectangle class has two data members (width and height) and a method called area. The area method calculates the area of the rectangle by multiplying its width and height.

To call the area method on a Rectangle object, you would use the dot (.) operator:

				
					Rectangle myRect; myRect.width = 5; myRect.height = 10; int myArea = myRect.area(); // returns 50 
				
			

Note that the area method is declared inside the class definition with the int return type, just like a regular function. The method definition includes the function body, which can access the width and height data members using the this pointer (which is a pointer to the object itself). In the example above, this->width and this->height are equivalent to width and height, respectively.

It is also possible to define a class method outside of the class definition using the :: scope resolution operator:

				
					class Rectangle {
public:
  int width, height;

  int area();
};
int Rectangle::area() {
  return width * height;
}

				
			

This defines the area method outside of the class definition, but still within the Rectangle namespace. The :: operator is used to specify that the method belongs to the Rectangle class.

Join To Get Our Newsletter
Spread the love