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:

// 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).

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

void Person::introduce() {
    std::cout << "Hello, my name is " << name << " and I am " << age << " years old." << std::endl;
}

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:

// 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()

Last updated

Was this helpful?