PDFVersion
No ads? No problem! Download the PDF book of this tutorial for just $24.99. Your support will help us reach more readers.
Thank You!
Introduction to C++ Structures:
A structure in C++ is a composite data type that comprises one or more variable types. Unlike arrayswhere all elements must be of the same data type, structures allow each element, called a member, to be of a different data type. Structures enable users to combine data items of various kinds, making them useful for representing records or collections of related data.
For instance, consider a scenario where we want to manage information about books in a library. We might need to track attributes such as title, author, subject, and book ID. In this case, each book can be represented as a structure with four members: title, author, subject, and book ID.
After determining the members of a structure, we specify the data type for each member. Typically, character arrays are used for textual data, while integers or floating-point numbers are used for numerical data.
Structures can have an associated name known as a structure tag. Although not mandatory, defining a structure tag is considered good practice. A structure tag serves as a label for the structure's format and is not a variable name. Unlike array names, which reference arrays as variables, a structure tag simply defines the structure's layout.
It's essential to note the distinction between control structures (like sequences, selections, and loops) and data structures. Control structures dictate the flow of a program's instructions, while data structures encapsulate related data fields.
In C++, structures are syntactically defined using the struct
keyword, followed by the structure's name and its members enclosed in curly braces. Each member consists of a data type followed by an identifier. For example:
struct Library {
char title[100];
char author[100];
char subject[100];
int bookID;
} libraryObject;
Remember to include a semicolon ;
after the closing curly brace in the structure definition, as it's crucial for proper compilation. The structure tag ("Library" in this case) serves as the model for the structure type, while "libraryObject" is an optional parameter representing an instance of the structure.
Naming conventions for structure tags follow the same rules as variable names. By defining a structure tag, we inform C++ about the structure's format and the types of its elements.
If we include the structure parameter (Library in the example above) in the structure definition, it becomes a valid type name equivalent to the structure. Thus, we can declare objects of that type without using the struct
keyword.
In C++, the arrow operator ->
and the dot operator .
are used to access members of a structure or class. The arrow operator is typically used with pointers to structures or classes, while the dot operator is used with structure or class instances.
The arrow operator allows access to members through a pointer, making it suitable for both pointer and non-pointer access scenarios. In contrast, the dot operator accesses members directly without involving pointers.
Below are examples of syntaxes to access members of the Library struct using both the dot (.) and arrow (->) operators:
// Define a structure named Library
struct Library {
char title[100];
char author[100];
char subject[100];
int bookID;
};
// Create an instance of the Library structure
Library libraryObject;
/* Access members using the dot operator. */
// Assign a value to the bookID member
libraryObject.bookID = 12345;
// Print the value of bookID
cout << "Book ID: " << libraryObject.bookID << endl;
// Create a pointer to the Library structure
Library *libraryPtr = &libraryObject;
/* Access members using the arrow operator. */
// Assign a value to the bookID member using the arrow operator
libraryPtr->bookID = 54321;
// Print the value of bookID using the arrow operator
cout << "Book ID: " << libraryPtr->bookID << endl;
To access members of a structure, we use the dot .
operator followed by the member name. This syntax is used to access individual members of a structure instance.
For instance, given a structure Car with members name, model, and price, we can access these members for specific Car objects like BMW, Mercedes, etc., using dot notation:
BMW.name;
BMW.model;
BMW.price;
Each of these accesses returns the corresponding data type defined for the respective member.
Below is an example demonstrating the usage of structures in C++, illustrating how to define a structure, create structure objects, and access their members:
#include<iostream>
#include<string>
using namespace std;
struct Car {
string name;
string model;
float price;
};
int main() {
Car BMW; // Creating a Car object
cout << "Enter the Name of Car: ";
getline(cin, BMW.name);
cout << "Enter the Model of Car: ";
getline(cin, BMW.model);
cout << "Enter the Price of Car in $: ";
cin >> BMW.price;
cout << "\n\nCar Information:" << endl;
cout << "Car Name: " << BMW.name << endl;
cout << "Car Model: " << BMW.model << endl;
cout << "Car Price: $" << BMW.price << endl;
return 0;
}
In addition to individual structure objects, we can create arrays of structures to manage multiple related data items efficiently. This facilitates operations such as sorting, searching, and manipulation of structured data.
The typedef keyword in C++ allows us to create aliases or alternate names for existing data types, including structures. This can enhance code readability, portability, and self-documentation. By defining aliases, we can refer to complex types with more meaningful names, improving code clarity.
For example:
typedef struct {
char bookName[50];
char authorName[50];
int year;
} Books;
Books Book1, Book2;
Here, Books serves as an alias for the structure containing book details. We can then declare variables (Book1 and Book2) of this type without explicitly using the struct keyword.
In C, structures were commonly used to organize related data, whereas in C++, classes have largely replaced structures. However, in C++, the distinction between structures and classes isn't as rigid as in C. Here are the key differences between structures and classes in C++:
Default Member Access:- In a class, members are private by default, meaning they cannot be accessed directly from outside the class.
- In a struct, members are public by default, allowing them to be accessed freely from outside the struct.
- When a struct is derived from another class or struct, the default access specifier for the base class/struct members is public.
- Conversely, when a class is derived from another class, the default access specifier for the base class members is private.
These differences reflect the historical distinctions between structures and classes in C, but in modern C++, the choice between using a class or struct often comes down to stylistic and semantic considerations rather than strict technical differences.
Sardar Omar
I did my hardest to present you with all of the information you need on this subject in a simple and understandable manner. However, if you have any difficulties understanding this concept or have any questions, please do not hesitate to ask. I'll try my best to meet your requirements.