C++ Struct Public
We frequently encounter situations when we need to store groups of data, regardless of whether they are of the same data type. We are all familiar with arrays in C++, which store data collections with uniform data types near one another in memory.
Unlike arrays, custom-defined data types called C++ structures act as containers for collections of objects with various data types. These frameworks enable us to combine data types to build a cohesive unit.
What is Structure?
A struct is a user-defined data structure that collects variables of various data kinds under a single name in the C++ programming language. Although some significant distinctions exist between member visibility and default access, it is comparable to a class.
Working with Public Members in a C++
When working with public members of a C++ struct, a struct must be built that makes its data and functions directly accessible to outside programs. The struct's public members are those you define in its definition; these can be changed and used without getter or setter methods.
You may quickly access the struct's public members and call member functions by making an instance. This method makes coding for simple cases easier. In more complicated circumstances, it is necessary to carefully weigh the benefits of direct access against the potential negatives of lower encapsulation and data integrity control.
In C++, a struct's members are all made public by default when declared. This indicates no limitations on accessing or changing members directly from outside the structure. A struct with public members might resemble the following:
Syntax:
struct StructName {
// Public members
data_type member1;
data_type member2;
// ... more members
// Public member functions (optional)
return_type function1(parameters) {
// function implementation
}
return_type function2(parameters) {
// function implementation
}
// ... more functions
};
C++ Structure Contains the following Members
- Data Members: These parts are made up of standard C++ variables. They enable us to build a structure in C++ that supports variables of various data kinds.
- Member Functions: These elements are made up of regular C++ functions. It is possible to include functions in a structure declaration in addition to variables.
Example:
When a struct is defined in C++ as having public members, it signifies that those members are immediately accessible and unrestricted from outside the struct. It's commonly known as "public access."
#include <iostream>
#include <string>
using namespace std;
// Define a struct named 'Sample'
struct Sample {
// Public members
string greetings;
int rollno;
double marks;
//Constructor to initialize members
Sample(const string& _greetings, int _rollno, double _marks)
: greetings(_greetings), rollno(_rollno), marks(_marks) {}
// Public member function to perform an action
void action() {
cout << "The welcome message is: " << greetings << endl;
cout << "The roll number is: " << rollno << endl;
cout << "The marks obtained is: " << marks << " for 100" << endl;
}
};
int main() {
// Create an instance of the 'Sample' struct
Sample sample("Tutorials and examples", 21, 94);
// Call the 'action' member function to display the information
sample.action();
return 0;
}
Output:
![C++ Struct Public](https://static.tutorialandexample.com/cpp/cpp-struct-public1.png)
Explanation:
Step 1: The first step includes the required input/output (iostream) and string operations (string) header files.
Step 2: To access standard library components more conveniently, use the std namespace.
Step 3: Create a Sample struct with three public members: double marks, int rollno, and string greetings.
Step 4: Declare the string greetings, int rollno, and double marks as public elements inside the Sample struct.
In the main () function,
step 5:
Make a sample instance of the Sample struct.
Give the sample instance's public members' values.
Step 6: Use cout and the instance's member variables to access and display the public member values directly.
Step 7: Have the main () method return 0 to show success.
Step 8: Compile the program and execute it to get the results.
Example 2:
In this example, we take width and height as input and print the rectangle area using C++ struct public members.
#include <iostream>
#include <string>
using namespace std;
// Define a struct named 'Areaofrectangle.'
struct Areaofrectangle {
//Declare public members' width and height
double w;
double h;
//Constructor to initialize members
Areaofrectangle(double _w, double _h)
: w(_w), h(_h) {}
// Public member function to calculate the area
double area() {
return w * h;
}
};
int main() {
// Create an instance of the 'Areaofrectangle' struct
Areaofrectangle rect(5.0, 3.0);
cout << "The given Width value w is: " << rect.w << endl;
cout << "The given Height value h is: " << rect.h << endl;
cout << "The Area for the width mentioned above and height is: " << rect.area() << endl;
return 0;
}
Output:
![C++ Struct Public](https://static.tutorialandexample.com/cpp/cpp-struct-public2.png)
The above-provided code serves as an example of how to compute and show the area of a rectangle using a C++ struct with public elements. The necessary header files for input/output and string operations are first included. It has been determined that the Areaofrectangle struct has two public members: w for width and h for height. These members can be accessed and changed outside of the struct. The Constructor initializes the w and h members, and the area() member function determines the rectangle's area by multiplying w and h. A struct instance is created in the main() function, and its public members are accessed and shown. The computed area is then displayed.
Advantages of C++ Struct Public
Using public members in a C++ struct might provide several benefits. Here are a few advantages:
- Simple and Accessible: The struct's data and functions are accessible from any area of the program due to its public members. This can make the code simpler and reduce the requirement for extra accessor methods.
- Direct Manipulation: Public members allow direct manipulation of the values of a struct's variables without using getter and setter procedures. This may result in a more concise code.
- Code Readability: Public members frequently result in better readable code, especially in smaller projects, because you can see how the members are utilized and changed immediately.
- Performance: Since calling getter and setter methods cost the cost of function calls, direct access to public members may be more effective.
- Simpler Initialization: When constructing an instance of a structure with public members, you can initialize the variables directly. This may result in an initialization code that is clearer and shorter.
- Learning and Teaching: Since they more clearly illustrate the concepts of encapsulation and access control, public members can be useful when explaining or learning the fundamentals of structs and object-oriented programming.
- Less Boilerplate Code: Using public members helps minimize the boilerplate code and provides a cleaner codebase by reducing the requirement to write accessor (getters and setters) methods.
Disadvantages of C++ Struct Public
- Lack of Encapsulation: Encapsulation is broken when public members expose the structure's underlying architecture to the outside world. This might result in unauthorized access to and alteration of the data, which makes it more difficult to maintain and debug the code.
- Data Integrity: The public permits Direct data editing without validation or checks. Because of This may lead to consistent or accurate data states, which could cause unexpected program behaviour.
- Limited Control: You need more control over who can access and change your data when you have public members. Because of this, it could be challenging to impose limitations or guidelines on how the data should be treated.
- Limited flexibility: Public elements can restrict your ability to modify and enhance the implementation of the structure without affecting the external code that depends on those members.
Security Issues: If sensitive data is not properly protected, the direct exposure of data through public members may cause security issues.