Understanding Structs in C++
C++ | Tips
GitHub Repo:
Structs are one of the foundational features in C++, allowing us to group related data together under a single type. They’re useful for keeping code organized, clean, and readable — especially when handling objects with multiple attributes. In this post, we’ll explore how structs work in C++ with a series of examples, from basics to advanced struct techniques.
What is a Struct?
A struct
in C++ is a way to define a custom data type that groups variables under one name. Each variable within a struct is called a "member." Unlike classes, structs have public members by default, making them accessible directly.
Let’s dive into examples to understand struct usage better.
Example 1: A Simple Struct
In this first example, we define a simple struct for a product, Product
, containing basic details like name, category, price, and stock level.
#include <iostream>
struct Product {
std::string name;
std::string category;
double price;
int stock;
};
// Function to update stock
void SetStock(Product& p, int stock) {
p.stock = stock;
}
int main() {
Product p1;
p1.name = "iPhone 16";
p1.category = "Smartphone";
p1.price = 1220.00;
p1.stock = 12;
std::cout << "Product Name: " << p1.name << std::endl;
std::cout << "Stock: " << p1.stock << std::endl;
SetStock(p1, 3);
std::cout << "Updated Stock: " << p1.stock << std::endl;
return 0;
}
Product Name: iPhone 16
Stoke: 12
Updated Stoke: 3
Example 2: Adding Member Functions to Structs
Structs in C++ can also contain member functions, which makes them even more powerful. Let’s add a displayProduct
function to show product details and an updateStock
function to adjust stock levels directly from within the struct.
struct Product {
std::string name;
std::string category;
double price;
int stock;
void displayProduct() const {
std::cout << "Product: " << name << "\nCategory: " << category
<< "\nPrice: $" << price << "\nStock: " << stock << std::endl;
}
void updateStock(int newStock) {
stock = newStock;
std::cout << "Updated stock to: " << stock << std::endl;
}
};
int main() {
Product p1{"iPhone 16", "Smart Phone", 1220.00, 12};
p1.displayProduct();
p1.updateStock(3);
return 0;
}
Product: iPhone 16
Category: Smart Phone
Price: $1220
Stock: 12
Updated stock to: 3
Example 3: Using Arrays of Structs
For handling multiple instances of Product
, we can create an array of structs.
Product products[] = {
{"iPhone 16", "Smartphone", 1220.00, 12},
{"MacBook Air", "Laptop", 1500.00, 5},
{"Tablet", "Electronics", 600.00, 10}
};
for (const auto& product : products) {
product.displayProduct();
std::cout << "------------------" << std::endl;
}
Product: iPhone 16
Category: Smartphone
Price: $1220
Stock: 12
------------------
Product: MacBook Air
Category: Laptop
Price: $1500
Stock: 5
------------------
Product: Tablet
Category: Electronics
Price: $600
Stock: 10
------------------
Example 4: Using Structs with STL Containers
Arrays are fine, but sometimes you need a more flexible structure. We can use C++’s Standard Library (STL) to store structs in containers like std::vector
, which allows dynamic resizing.
#include <vector>
std::vector<Product> inventory = {
{"iPhone 16", "Smartphone", 1220.00, 12},
{"MacBook Air", "Laptop", 1500.00, 5},
{"Tablet", "Electronics", 600.00, 10}
};
for (const auto& item : inventory) {
item.displayProduct();
std::cout << "------------------" << std::endl;
}
Example 5: Adding a Constructor
Constructors in structs allow us to initialize members directly when creating a struct object. Let’s add a constructor to our Product
struct.
struct Product {
std::string name;
std::string category;
double price;
int stock;
Product(std::string n, std::string c, double p, int s)
: name(n), category(c), price(p), stock(s) {}
void displayProduct() const {
std::cout << "Product: " << name << "\nCategory: " << category
<< "\nPrice: $" << price << "\nStock: " << stock << std::endl;
}
};
int main() {
Product p2{"MacBook Air", "Laptop", 1500.00, 5};
p2.displayProduct();
return 0;
}
Product: MacBook Air
Category: Laptop
Price: $1500
Stock: 5
Example 6: Structs with Nested Structs
In C++, structs can contain other structs as members. Let’s add a Dimensions
struct to store length, width, and height for each product.
In this example, the Product
struct has a nested Dimensions
struct that contains details about the product's size.
struct Dimensions {
double length;
double width;
double height;
};
struct Product {
std::string name;
std::string category;
double price;
int stock;
Dimensions size;
void displayProduct() const {
std::cout << "Product: " << name << "\nCategory: " << category
<< "\nPrice: $" << price << "\nStock: " << stock
<< "\nDimensions (L x W x H): " << size.length
<< " x " << size.width << " x " << size.height << std::endl;
}
};
int main() {
Product p3{"Tablet", "Electronics", 600.00, 10, {10.2, 6.1, 0.3}};
p3.displayProduct();
return 0;
}
Product: Tablet
Category: Electronics
Price: $600
Stock: 10
Dimensions (L x W x H): 10.2 x 6.1 x 0.3
Conclusion
Structs in C++ are incredibly useful for organizing related data. From adding simple member variables to using STL containers and nested structs, we’ve covered various ways to use structs efficiently. They’re great for building more organized, readable, and maintainable C++ code.
Try incorporating structs into your projects and explore their versatility in C++ programming!