> For the complete documentation index, see [llms.txt](https://codexpress.gitbook.io/welcome-to-codexpress/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://codexpress.gitbook.io/welcome-to-codexpress/object-oriented-programming/c++-oops/classes.md).

# Classes

Classes are a fundamental concept in C++ that allow you to create user-defined data types. They are used to define the blueprint for objects, which are instances of a class. Here's a tutorial on how to work with classes in C++:

#### 1. Class Declaration:

To declare a class, you typically create a header file (.h or .hpp) for the class and define the class in it. Let's create a simple class called `Person`:

```cpp
// Person.h
#pragma once

class Person {
public:
    // Member variables (data members)
    std::string name;
    int age;

    // Member functions (methods)
    void introduce();
};
```

In the example above, we've declared a class `Person` with two member variables (`name` and `age`) and a member function (`introduce`).

#### 2. Class Definition:

Now, let's define the member functions of the `Person` class in a separate source file (.cpp).

<pre class="language-cpp"><code class="lang-cpp"><strong>// Person.cpp
</strong>#include "Person.h"
#include &#x3C;iostream>

void Person::introduce() {
    std::cout &#x3C;&#x3C; "Hello, my name is " &#x3C;&#x3C; name &#x3C;&#x3C; " and I am " &#x3C;&#x3C; age &#x3C;&#x3C; " years old." &#x3C;&#x3C; std::endl;
}
</code></pre>

Here, we define the `introduce` method to print the person's name and age.

#### 3. Creating Objects:

To use the `Person` class, you need to create objects of that class in your main program:

```cpp
// main.cpp
#include <iostream>
#include "Person.h"

int main() {
    // Create Person objects
    Person person1;
    Person person2;

    // Set data for person1
    person1.name = "Alice";
    person1.age = 30;

    // Set data for person2
    person2.name = "Bob";
    person2.age = 25;

    // Call the introduce method
    person1.introduce();
    person2.introduce();

    return 0;
}
```

#### 4. Accessing Members:

You can access the member variables and call member functions using the dot `.` operator. In our example, we set the `name` and `age` of `person1` and `person2`, and then called the `introduce` method on both objects.

```
Person.introduce()
```
