The second mechanism used to create User-Defined Types is a class. A class is made up of data and function members. A function that belongs to a class is called a Method.

Syntax

A Class consists of the following syntax:

class User_Defined_Type_Name{
private:
public:
};

The class keyword declares a class of type "User_Defined_Type_Name" and defines the data members within the class.

A class has a Constructor and Destructor method. The constructor method initializes the class to a safe state. The destructor cleans up after the class object is no longer needed. Furthermore, the constructor and destructor have the same name as the class.

For example, let's define a Student class with a Constructor and Destructor methods.

Line 1 shows the constructor of the class. Line 2 illustrates the destructor of the class. Notice the tilde symbol "~" prefixed to the destructor's name.

In practice, you create a class object as shown in the snippet below (line 3). Upon creation of the object, the constructor method is called. When the class object is destroyed, the destructor method is called.

int main(){
Student harold; //3. Create a class object
return 0;
}

Access Specifiers

As mentioned, a class contains data members and methods. These members can be accessed through the dot operator "." However, their access is controlled by the class Access Specifier.

There are three kinds of Access Specifier: Public, Private or Protected. Members declared within the Private Access Specifier are not accessible outside the class. Whereas, members declared within the Public Access Specifier are accessible outside the class.

For example, line 1 shows the data member "age" defined within the private access specifier.

In practice, you create a class object as shown in the snippet below (line 1).

Line 2 shows how to set the value of "age" using the "setAge" method. Line 3 shows how to retrieve the value of "age" using the "getAge" method. Lastly, the age is printed in line 4.

int main(){
Student harold; //1. Create a class object
harold.setAge(29); //2. set age to 29
int studentAge=harold.getAge(); //3. get the current age
std::cout<<"Age: "<<studentAge<<std::endl; //4. print the age
return 0;
}

Now that you know about classes, it's time to learn about the new and delete operators utilized in the creation and destruction of a class.