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.
We can define a function that belongs to a class in C++ in the following ways:
In the code example below, we'll create a class myclass
and define a method mymethod
inside the class.
Let's look at the example below:
#include <iostream>using namespace std;// Creating a classclass myclass { // This is the classpublic: // This is an Access specifiervoid mymethod() { // This is the methodcout<<"Hi how are you today?";}};// creating an object of the classint main(){myclass myobject; // we create an object myobjectmyobject.mymethod(); // calling the methodreturn 0;}
class
keyword to create a class myclass
.public
keyword to specify that the attributes and methods (class members) are accessible from outside the class.mymethod
.myobject
.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.
Let's look at the code below:
#include <iostream>using namespace std;// Creating a classclass myclass { // This is the classpublic: // This is an Access specifiervoid mymethod(); // This is the method};// defining the method outside the classvoid myclass::mymethod(){cout<<"Hi how are you today?";}// creating an object of the classint main(){myclass myobject; // we create an object myobjectmyobject.mymethod(); // calling the methodreturn 0;}
The above code works same as the previous one except in line 17 we declare the method mymethod
outside the class myclass
.