In this article, you’ll learn about C++ Structure (User-defined datatypes ) with the help of Example.
Structure is a collection of variables of different data types under a single name. It allows different variables to be accessed by using a single pointer to the structure.
How to declare a structure in C++ programming?
Table of Contents
The struct
keyword defines a structure type followed by an identifier (name of the structure).
Then inside the curly braces, you can declare one or more members (declare variables inside curly braces) of that structure.
SYNTAX
struct structure_name { data_type member1; data_type member2; . . data_type memeber; };
How to define a structure variable?
Once you declare a structure. You can define a structure variable as
SYNTAX
Class_name variable_name;
When structure variable is defined, only then the required memory is allocated by the compiler.
How to access members of a structure?
The members of structure variable is accessed using a dot (.) operator.
Suppose, you want to access House of structure variable room_no and assign it 50 to it. You can perform this task by using following code below:
House.room_no = 50;
Advantages
- It can hold variables of different data types.
- We can create objects containing different types of attributes.
- It allows us to re-use the data layout across programs.
- It is used to implement other data structures like linked lists, stacks, queues, trees, graphs etc.
Example: C++ Structure
C++ Program to assign data to members of a structure variable and display it.
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
Person p1;
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;
return 0;
}
Code language: PHP (php)
Output
Enter Full name: Magdalena Dankova Enter age: 27 Enter salary: 1024.4 Displaying Information. Name: Magdalena Dankova Age: 27 Salary: 1024.4
Here a structure Person is declared which has three members name, age and salary.