struct


Keyword: struct in C++

A struct in C++ is a user-defined data type that groups related data elements together under a single name. It's similar to a class but with different default access specifiers. Structs are commonly used to represent simple data structures and are a fundamental feature in C++, inherited from the C language but enhanced with object-oriented capabilities.

Key Characteristics

Example 1: Basic Struct Definition and Usage

#include <iostream>
#include <string>

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

int main() {
    Person person1;
    person1.name = "Alice";
    person1.age = 30;
    person1.height = 1.65;

    Person person2 = {"Bob", 25, 1.80};

    std::cout << person1.name << " is " << person1.age << " years old and " 
              << person1.height << "m tall." << std::endl;
    std::cout << person2.name << " is " << person2.age << " years old and " 
              << person2.height << "m tall." << std::endl;

    return 0;
}

Explanation:

Example 2: Struct with Member Functions and Constructor

#include <iostream>
#include <string>

struct Rectangle {
    double width;
    double height;

    Rectangle(double w, double h) : width(w), height(h) {}

    double area() const {
        return width * height;
    }

    void scale(double factor) {
        width *= factor;
        height *= factor;
    }
};

int main() {
    Rectangle rect(5.0, 3.0);
    std::cout << "Area: " << rect.area() << std::endl;

    rect.scale(2.0);
    std::cout << "Scaled area: " << rect.area() << std::endl;

    return 0;
}

Explanation:

Example 3. Nested Structs and Inheritance

#include <iostream>
#include <string>
#include <vector>

struct Address {
    std::string street;
    std::string city;
    std::string country;
};

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

struct Employee : Person {
    int employeeId;
    double salary;

    void displayInfo() const {
        std::cout << "Name: " << name << ", ID: " << employeeId 
                  << ", Salary: $" << salary << std::endl;
        std::cout << "Address: " << address.street << ", " 
                  << address.city << ", " << address.country << std::endl;
    }
};

int main() {
    Employee emp;
    emp.name = "Charlie";
    emp.age = 35;
    emp.address = {"123 Main St", "Anytown", "USA"};
    emp.employeeId = 1001;
    emp.salary = 50000.0;

    emp.displayInfo();

    return 0;
}

Explanation: - Address is a nested struct within Person. - Employee inherits from Person, demonstrating struct inheritance. - The displayInfo function shows how to access inherited and nested struct members.

Example 4: Struct as Function Parameter and Return Type

#include <iostream>
#include <string>
#include <vector>

struct Point {
    double x, y;
};

struct Polygon {
    std::vector<Point> vertices;
};

// Function taking struct as parameter
double distanceBetweenPoints(const Point& p1, const Point& p2) {
    double dx = p2.x - p1.x;
    double dy = p2.y - p1.y;
    return std::sqrt(dx*dx + dy*dy);
}

// Function returning struct
Point midpoint(const Point& p1, const Point& p2) {
    return {(p1.x + p2.x) / 2, (p1.y + p2.y) / 2};
}

int main() {
    Point a = {0, 0};
    Point b = {3, 4};

    std::cout << "Distance: " << distanceBetweenPoints(a, b) << std::endl;

    Point mid = midpoint(a, b);
    std::cout << "Midpoint: (" << mid.x << ", " << mid.y << ")" << std::endl;

    Polygon triangle;
    triangle.vertices = {{0, 0}, {1, 0}, {0, 1}};

    std::cout << "Triangle vertices:" << std::endl;
    for (const auto& vertex : triangle.vertices) {
        std::cout << "(" << vertex.x << ", " << vertex.y << ")" << std::endl;
    }

    return 0;
}

Explanation:

Additional Considerations

  1. Memory Layout: Structs have a defined memory layout, making them useful for interfacing with hardware or external data formats.

  2. Padding: Be aware of potential padding between struct members, which can affect the total size of the struct.

  3. POD (Plain Old Data): Structs without user-defined constructors, destructors, or virtual functions are considered POD types, which have special properties in C++.

  4. Default Member Initialization: C++11 and later allow in-class member initializers for structs.

  5. Aggregate Initialization: Structs support aggregate initialization, allowing initialization with a brace-enclosed list of values.

Summary

Structs in C++ are versatile user-defined types that offer several key features:

  1. Group related data elements under a single name.
  2. Provide public access to members by default.
  3. Can include member functions, constructors, and destructors.
  4. Support inheritance and polymorphism.
  5. Useful for creating simple data structures and POD types.

Key points to remember:

Best practices:

Structs in C++ provide a straightforward way to group related data and are particularly useful for creating simple, public data structures. Their flexibility and compatibility with C make them a valuable tool in many C++ programming scenarios.

Previous Page | Course Schedule | Course Content