Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

User-defined Data Types in C++

Introduction

In C++, user-defined data types allow programmers to create their own data types, which can be tailored to their specific needs. These data types are built upon the fundamental data types provided by C++ but offer more flexibility and functionality. The primary user-defined data types in C++ include structures, classes, and unions.

Structures

A structure is a collection of variables, possibly of different types, grouped together under a single name. Structures are used to represent a record. To define a structure, the struct keyword is used.

Example

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

In the example above, a structure named Person is defined with three members: name, age, and height.

Classes

A class is a blueprint for creating objects. It encapsulates data for the object and methods to manipulate that data. A class is defined using the class keyword.

Example

class Car {
public:
    std::string brand;
    std::string model;
    int year;

    void displayInfo() {
        std::cout << "Brand: " << brand << std::endl;
        std::cout << "Model: " << model << std::endl;
        std::cout << "Year: " << year << std::endl;
    }
};

In the example above, a class named Car is defined with three public data members: brand, model, and year. It also contains a member function displayInfo to display the car's information.

Unions

A union is a special data type that allows storing different data types in the same memory location. A union is defined using the union keyword.

Example

union Data {
    int i;
    float f;
    char str[20];
};

In the example above, a union named Data is defined with three members: i (an integer), f (a float), and str (a character array).

Enum

An enum (enumeration) is a user-defined data type that consists of integral constants. Each integral constant is assigned a name. The keyword enum is used to define enumerations.

Example

enum Color {
    RED,
    GREEN,
    BLUE
};

In the example above, an enumeration named Color is defined with three constants: RED, GREEN, and BLUE.

Typedef

The typedef keyword is used to create an alias for another data type. This can make complex declarations simpler and more readable.

Example

typedef unsigned long ulong;
ulong distance;

In the example above, typedef is used to create an alias ulong for the data type unsigned long.