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 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; }
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 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; }
The above code works same as the previous one except in line 17 we declare the method mymethod
outside the class myclass
.
RELATED TAGS
CONTRIBUTOR
View all Courses