A class in C++ is a user-defined data type used to create objects.
C++ is an object-oriented programming language (OOP). Thus, it has to do with classes and objects along with their attributes and methods. In real life, for example, a computer mouse is an object. The mouse has attributes, including its color, size, and texture, and methods, including scroll and click.
These attributes and methods are simply variables and functions that belong to a class. They are referred to as class members.
In short, a class is simply an object constructor.
To create a class in C++, we use the class
keyword.
Now let us create a class we call myClass
.
class myClass { // This is the classpublic: // This is an Access specifierint mynumber; // This is an Attributestring mystring; // This is an Attribute};
class
keyword to create a class myClass
.public
keyword to specify that the attributes and methods (class members) are accessible from outside the class.mynumber
and mystring
inside the class. These variables are the attributes of the class
.To create an object of a given class, we specify the name of the class
, followed by the name of the object.
In the code below, we will create an object for the class myclass
we created earlier. The attributes of the class are accessed using the .
syntax on the object.
#include <iostream>#include <string>using namespace std;// creating the classclass myClass { // This is the classpublic: // This is an Access specifierint mynumber; // This is an Attributestring mystring; // This is an Attribute};// creating the object of myclassint main() {myClass myobject;// Accessing the attributes of the classmyobject.mynumber = 10;myobject.mystring = "I love C++";// printing the valuescout <<myobject.mynumber << "\n";cout <<myobject.mystring;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
.mynumber
and mystring
inside the class. These variables are the attributes of the class.myobject
of myclass
.mynumber
of myobject
.mystring
of myobject
.myobject
.