Home

 › 

Articles

 › 

Understanding Data Types in C++, With Examples

Vector in C++ STL

Understanding Data Types in C++, With Examples

Key Points

  • Data types are fundamental blocks in programming languages and are essential for manipulating data.
  • Data types can be categorized as basic, derived, or user-defined.
  • Basic data types in C++ include integers, floating-point numbers, characters, booleans, and void.
  • Derived data types in C++ include arrays, pointers, and references.
  • User-defined data types in C++ are created by programmers and can be more complex, such as enumerations, structures, and classes.

Data types represent the fundamental blocks that construct virtually all programming languages. Without correct typing of data, manipulating the data becomes very unmanageable. Before you can choose a suitable type for your data, it’s essential to understand what data types are and what options you have. In this article, we’re going to cover the data types that are frequently used in C++, and how and when to use them.

What Are Data Types?

Data type refers to how the data is represented in code and what characteristics it has. The data type restricts the properties of the data, what values it can have, and what operations can be used with it. Without data types, data would be unstructured and impossible to work with.

At a high level, we can categorize data into one of three types: basic (or primary), derived, or user-defined. Basic data types are built into the language and are the simplest to use. Derived data types build upon basic types, and hence tend to be more complex. User-defined types are created using basic types but can be implemented in specific ways depending on your needs. Next, we’ll examine these in more detail.

Basic Data Types in C++

As mentioned, basic or primitive data types are those that are already built in and are the most fundamental of all types. These include:

  • Integers – These are numeric types of data, representing whole numbers, either negative or positive. They can be “short”, “long” or “long long”, usually meaning a size of 2, 4, or 8 bytes, respectively.
  • Floating-point – These represent numbers with decimal places. Standard “float” represents one decimal place, while “double” represents two, and “long double” represents a more extended number.
  • Character – We use characters to represent individual, non-numeric characters, i.e. %, $ and B, C, etc.
  • Boolean – Logical values are indicated by a boolean, i.e. “true” or “false.”
  • Void – This is indicating the absence of a data type, usually used to return functions which don’t have an associated value.

Example Implementation

To see how to implement these data types, consider the following code:

#include <iostream>

int main() {
    int myInt = 42;
    short myShort = 10;
    long myLong = 123456;
    long long myLongLong = 123456789;

    float myFloat = 3.14f;
    double myDouble = 2.71828;
    long double myLongDouble = 1.61803398875;

    char myChar = 'A';

    bool myBool = true;

    std::cout << "Integer: " << myInt << std::endl;
    std::cout << "Short: " << myShort << std::endl;
    std::cout << "Long: " << myLong << std::endl;
    std::cout << "Long Long: " << myLongLong << std::endl;

    std::cout << "Float: " << myFloat << std::endl;
    std::cout << "Double: " << myDouble << std::endl;
    std::cout << "Long Double: " << myLongDouble << std::endl;

    std::cout << "Character: " << myChar << std::endl;

    std::cout << "Boolean: " << std::boolalpha << myBool << std::endl;

    return 0;
}

This is a relatively simple example. We start by including the standard input/output stream header file, then we declare the “main()” function. Within this, we declare variables for each of the basic data types we’ve discussed and then output the values to the console, as we can see in the image.

basic data types in C++.
Basic data types are the most fundamental type in C++.

©History-Computer.com

Derived Data Types in C++

As the name suggests, derived data types are based on primitive data types but are more complex. Within this category, we have:

  • Arrays – These are fixed-size collections of elements that share a data type, stored in a contiguous memory block. We can access array elements using an index.
  • Pointers – These variables store memory locations, directing to the location of a variable or object. Pointers are mostly used to allocate memory dynamically, but also to implement complex algorithms and access certain data structures.
  • References – These give an alternative name for a variable. References allow us to create several names for the same memory address and are often used to pass arguments by reference to a function. This lets us modify the initial variable.

Example Implementation

To demonstrate these data types, we have the following code:

#include <iostream>

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};

    std::cout << "Array elements: ";
    for (int i = 0; i < 5; ++i) {
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;

    int* ptr = nullptr;
    ptr = numbers;

    std::cout << "Pointer elements: ";
    for (int i = 0; i < 5; ++i) {
        std::cout << *(ptr + i) << " ";
    }
    std::cout << std::endl;

    int x = 10;
    int& ref = x;

    std::cout << "Original value of x: " << x << std::endl;
    std::cout << "Value through reference: " << ref << std::endl;

    ref = 20;

    std::cout << "Modified value of x: " << x << std::endl;

    return 0;
}

Here, we declare an array, “numbers”, of size 5 and initialize it using the “int [array name][number of elements] = {[elements]” syntax. We then use a for loop to iterate over the elements in the array, and print them to the console.

Next, we declare the “ptr” pointer and assign it to the memory location of the array, and access the elements via the indices.

After that, we declare a variable, “x”, and create a reference, “ref”, that refers to it. The value of x is printed, and then we access the value through the reference. After modifying it, the modified value is printed as well.

derived data types in C++.
Derived data types are more complex than primitive types.

©History-Computer.com

User-Defined Data Types in C++

The last kind of data type is known as user-defined. These are ones that programmers can create as and when they’re required, and to suit their needs. While they’re based on the basic data types, they often organize data in a more complicated manner.

The user-defined types are:

  • Structures – These group together variables of different types, allowing you to organize your data coherently.
  • Classes – These are essentially the foundation of all object-oriented programming (OOP) languages and help enforce encapsulation, polymorphism, and inheritance. Data and functions can be combined into a single entity using classes.
  • Enumerations – These can be used to define a set of constant values that have names so that you can create a new type that has discrete values within it.

Example Implementation

To show these data types, we’ve used the following example:

#include <iostream>

enum class Color {
    RED,
    GREEN,
    BLUE
};

struct Person {
    std::string name;
    int age;
};

class Circle {
private:
    double radius;

public:
    void setRadius(double r) {
        radius = r;
    }

    double getArea() {
        return 3.14 * radius * radius;
    }
};

int main() {
    Color color = Color::RED;

    Person person;
    person.name = "John Doe";
    person.age = 25;

    Circle circle;
    circle.setRadius(5.0);
    double area = circle.getArea();

    std::cout << "Color: " << static_cast<int>(color) << std::endl;
    std::cout << "Person: " << person.name << ", " << person.age << " years old" << std::endl;
    std::cout << "Circle area: " << area << std::endl;

    return 0;
}

We define the enumeration data type with 3 colors, a “Person” structure with two members (“age” and “name”), and the “Circle” class with the “radius” member and two member functions, “setRadius()” and “getArea().”

The “main()” function is then used to create instances of each data type. We initialize the “color” variable to “RED”, declare the “person” variable and assign a name and age, and declare the “circle” variable and pass a radius argument. The area of the circle is then calculated by calling the associated functions and is printed to the console, preceded by the name and age of the person variable, and the numerical representation of the assigned color variable.

user-defined data types in C++.
User-defined data types can be created as required and are the basis of OOP.

©History-Computer.com

Wrapping Up

In summary, there are many data types in C++, from basic types to more complex derived types and user-defined types, increasing in complexity. To work with C++ effectively, an understanding of how each type is used is crucial. Basic data types represent the building blocks of managing and using data, and the other data types extend from these. Derived data types enable us to group related data and implement more complicated structures. User-defined data types are more advanced, and mostly used to encapsulate data so we can make better sense of our code. When making decisions about how to proceed with your project, it’s sensible to consider all the data types at your disposal.

Summary Table

Data Type CategoryData TypesExample Implementation
Basic Data Types in C++Not specified in the contentVariables for each of the basic data types are declared and then output the values to the console.
Derived Data Types in C++Not specified in the contentAn array is declared and initialized. A pointer is declared and assigned to the memory location of the array. A variable is declared and a reference that refers to it is created.
User-Defined Data Types in C++Not specified in the contentAn enumeration data type, a structure, and a class are defined. Instances of each data type are created and initialized.

Frequently Asked Questions

What are data types in C++?

Data types are used to define the kind of data that we can work with within a program. They’re used to indicate the size of the values and the operations that can be performed on them.

What are the basic data types in C++?

The basic data types include integers (whole numbers), floating-point numbers (those with decimal places), characters (i.e. $, #, or letters), and boolean values (logical values, i.e. true or false).

What are the derived data types in C++?

Derived data types build upon the fundamental types, and are used to group related data into more complex structures. They include arrays, pointers, and references. Arrays are collections of related elements, i.e. integers or characters, pointers direct to memory locations of variables or objects, and references allow us to create several names for one memory location and modify a variable.

What are user-defined data types in C++?

User-defined types are more advanced and are created at the programmer’s discretion. They include structures (group unrelated data types together), classes (enforce encapsulation, inheritance, and polymorphism by grouping data and methods together), and enumerations (define a set of named constant values).

How can I convert one data type into another?

You can use casting operators to convert data from one type to another, i.e. static_cast, or dynamic_cast.

What's the difference between a structure and a class in C++?

These data types are similar, but not the same. Both can group unrelated entities together, but structures are usually public by default. On the other hand, classes are usually private by default. However, you can explicitly specify various access modifiers, i.e. public, private, or protected, for both classes and structures.

Can you use user-defined operators with user-defined types?

Yes, you can take advantage of operator overloading to specify how the operators behave for a particular data type. This gives you a greater degree of customization.

To top