C++ Class Methods

Methods, also known as member functions, are functions that belong to a class and define the behavior of objects created from the class. In this article, we will explore the basics of C++ class methods, including how to declare and define class methods inside and outside of the class definition.

Declaring Class Methods Inside the Class Definition

One way to define class methods is to declare them inside the class definition. To do this, simply write the function prototype inside the class body. For example, consider the following code:

1class Rectangle { 2 int width, height; 3 public: 4 void setWidth(int w) { 5 width = w; 6 } 7 void setHeight(int h) { 8 height = h; 9 } 10 int getArea() { 11 return width * height; 12 } 13};

In this example, we declare three class methods inside the class definition: setWidth, setHeight, and getArea. These methods can be called on objects of the Rectangle class to set the width and height of a rectangle and to return the area of a rectangle, respectively.

Defining Class Methods Outside the Class Definition

Another way to define class methods is to declare them outside the class definition. To do this, write the function prototype inside the class definition and the full function definition outside the class definition. For example, consider the following code:

1class Rectangle { 2 int width, height; 3 public: 4 void setWidth(int w); 5 void setHeight(int h); 6 int getArea(); 7}; 8 9void Rectangle::setWidth(int w) { 10 width = w; 11} 12 13void Rectangle::setHeight(int h) { 14 height = h; 15} 16 17int Rectangle::getArea() { 18 return width * height; 19}

In this example, we declare the class methods setWidth, setHeight, and getArea inside the class definition as prototypes and define the full functions outside the class definition. The syntax for defining the functions outside the class definition is as follows: return_type ClassName::function_name(parameters).