Language: EN

cpp-clases

What are Classes and How to Use Them in C++

In C++ a CLASS is a data type that groups data and functions under a single name and represents a concept or entity from the real world.

Classes provide a template to create instances of the class. Each instance has its own state *(stored in fields) and behavior (defined in methods).

Classes allow us to encapsulate related data and functionalities, making it easier to reuse code and maintain our applications. They are the foundation of object-oriented programming.

If you want to learn more about Objects, Classes, and Instances
check the Object-Oriented Programming Course read more ⯈

Classes in C++

The basic syntax for defining a class in C++ is as follows:

class ClassName
{
public:
    // Field definitions
    DataType fieldName;

    // Property definitions (access methods)
    DataType getPropertyName() const;
    void setPropertyName(DataType value);

    // Method definitions
    ReturnType methodName(Parameters);
};
  • ClassName: This is the name of the class, which must be unique.
  • DataType: This is the data type of the fields and properties.
  • fieldName: This is the name of the field.
  • methodName: This is the name of the method.
  • ReturnType: This is the data type that the method returns.
  • Parameters: These are the variables used to pass information to the method.

Classes are generally defined in files with the .cpp or .h (header) extension.

Composition of a Class in C++

A class in C++ is composed of three main elements: fields (attributes), properties (access methods), and methods (member functions).

Person
  • stringbirthDate
  • stringidNumber
  • stringGreet()
  • stringSendEmail()

The fields represent the variables or data that are part of a class. These can be of different types, such as integers, strings, booleans, etc. Fields are how we store information within a class and allow us to manipulate it according to our needs.

The methods are the actions or behaviors that a class can perform. These can be functions that return a value or procedures that do not return anything. Methods allow us to modularize the code and break tasks into smaller, manageable parts.

Basic Example

To create a class in C++, we use the keyword class followed by the class name and a list of members (fields and methods).

#include <iostream>
#include <string>

class Person
{
public:
    // Fields
    std::string Name;
    int Age;

    // Constructor
    Person(const std::string& name, int age)
        : Name(name), Age(age) {}

    // Method
    void Greet()
    {
        std::cout << "Hello, I am " << Name << " and I am " << Age << " years old!" << std::endl;
    }
};

int main()
{
    // Create an object of the Person class
    Person person("Juan", 25);

    // Call the Greet method
    person.Greet();

    return 0;
}

In this example, we have:

  • Defined a Person class with two fields (Name, Age).
  • Implemented a constructor that initializes these fields.
  • Defined a Greet method that prints a greeting with the person’s name and age.
  • Created an instance of Person and called the Greet method.

Using Classes

Creating Objects

To create an object of a class, we simply declare a variable of the class type and optionally call the constructor.

Person person("Ana", 30);

Accessing Fields and Properties

Fields and properties of a class are accessed using the dot notation (.).

std::cout << person.Name << std::endl;

Calling Methods

Methods of a class are also called using the dot notation (.).

person.Greet();

Inheritance and Polymorphism

C++ supports inheritance, which allows creating a new class based on an existing class, and polymorphism, which allows using methods from base and derived classes flexibly.

We will cover these concepts in the rest of the course

Practical Examples

Representation of a Person

Here we define a Person class that contains properties for the name and age, a constructor to initialize these values, and a method to greet.

#include <iostream>
#include <string>

class Person
{
private:
    std::string name;
    int age;

public:
    // Constructor
    Person(const std::string& name, int age)
        : name(name), age(age) {}

    // Method
    void Greet() const
    {
        std::cout << "Hello, I am " << name << " and I am " << age << " years old!" << std::endl;
    }
};

Representation of a Product

The Product class represents a product with properties for the name and price. It includes a constructor to initialize these fields and a method to display the product information.

#include <iostream>
#include <string>

class Product
{
private:
    std::string name;
    double price;

public:
    // Constructor
    Product(const std::string& name, double price)
        : name(name), price(price) {}

    // Method
    void ShowInformation() const
    {
        std::cout << "Product: " << name << ", Price: " << price << std::endl;
    }
};