How to create classes and objects in C++

Overview

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.

How to create a class

To create a class in C++, we use the class keyword.

Now let us create a class we call myClass.

Example

class myClass { // This is the class
public: // This is an Access specifier
int mynumber; // This is an Attribute
string mystring; // This is an Attribute
};
How to create a class

Explanation

  • Line 1: We use the class keyword to create a class myClass.
  • Line 2: We use the public keyword to specify that the attributes and methods (class members) are accessible from outside the class.
  • Lines 3-4: We create variables mynumber and mystring inside the class. These variables are the attributes of the class.

How to create an object

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.

Example

#include <iostream>
#include <string>
using namespace std;
// creating the class
class myClass { // This is the class
public: // This is an Access specifier
int mynumber; // This is an Attribute
string mystring; // This is an Attribute
};
// creating the object of myclass
int main() {
myClass myobject;
// Accessing the attributes of the class
myobject.mynumber = 10;
myobject.mystring = "I love C++";
// printing the values
cout <<myobject.mynumber << "\n";
cout <<myobject.mystring;
return 0;
}

Explanation

  • Line 6: We use the class keyword to create a class myclass.
  • Line 7: We use the public keyword to specify that the attributes and methods (class members) are accessible from outside the class.
  • Lines 8-9: We create variables mynumber and mystring inside the class. These variables are the attributes of the class.
  • Line 14: We create an object myobject of myclass.
  • Line 17: We access the attribute mynumber of myobject.
  • Line 18: We access the attribute mystring of myobject.
  • Lines 21-22: We print the results of the attributes of myobject.

    Free Resources