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
:
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).
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:
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.
Last updated
Was this helpful?