What are class methods in C++?

Overview

A class in C++ is defined as a user-defined data type that works as an object constructor.

It is similar to a computer mouse, an object with attributes, such as color and weight, and methods, such as scroll and click. A class creates objects that has methods. We can say that a method is a function that belongs to a class.

Defining a function

We can define a function that belongs to a class in C++ in the following ways:

  • Defining the method/function inside the class.
  • Defining the method/function outside the class.

Defining the function inside the class

In the code example below, we'll create a class myclass and define a method mymethod inside the class.

Example

Let's look at the example below:

#include <iostream>
using namespace std;
// Creating a class
class myclass { // This is the class
public: // This is an Access specifier
void mymethod() { // This is the method
cout<<"Hi how are you today?";
}
};
// creating an object of the class
int main(){
myclass myobject; // we create an object myobject
myobject.mymethod(); // calling the method
return 0;
}

Explanation

  • Line 5: We use the class keyword to create a class myclass.
  • Line 6: We use the public keyword to specify that the attributes and methods (class members) are accessible from outside the class.
  • Line 7: We create the method for the class mymethod.
  • Line 8: We create a block of code to be returned when the method is called.
  • Line 14: We create an object of the class myobject.
  • Line 15: We call the method for the function.

Defining the method outside the class

To perform this operation, it is necessary to define the method inside the class first and then proceed to define the same method outside the class. To do this, we specify the name of the class, followed by the operator :: (scope resolution), then followed by the name of the method.

In the code example below, we will create a class myclass and define a method mymethod outside the class.

Example

Let's look at the code below:

#include <iostream>
using namespace std;
// Creating a class
class myclass { // This is the class
public: // This is an Access specifier
void mymethod(); // This is the method
};
// defining the method outside the class
void myclass::mymethod(){
cout<<"Hi how are you today?";
}
// creating an object of the class
int main(){
myclass myobject; // we create an object myobject
myobject.mymethod(); // calling the method
return 0;
}

Explanation

The above code works same as the previous one except in line 17 we declare the method mymethod outside the class myclass.

Free Resources