C++ Programming
Topperworld.in
Structure
⚫ The structure is a user-defined data type that is available in C++.
⚫ Structures are used to combine different types of data types, just like
an array is used to combine the same type of data types.
⚫ A structure is declared by using the keyword “struct“.
⚫ When we declare a variable of the structure we need to write
the keyword “struct in C language but for C++ the keyword is not
mandatory
⚫ In C++, classes and structs are blueprints that are used to create the instance
of a class. Structs are used for lightweight objects such as Rectangle, color,
Point, etc.
⚫ Unlike class, structs in C++ are value type than reference type. It is useful if
you have data that is not intended to be modified after creation of struct.
⚫ C++ Structure is a collection of different data types. It is similar to the class
that holds different types of data.
Syntax:
struct
{
// Declaration of the struct
}
Example:
#include <iostream>
using namespace std;
struct Rectangle
{
int width, height;
};
©Topperworld
C++ Programming
int main(void) {
struct Rectangle rec;
rec.width=8;
rec.height=5;
cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<e
ndl;
return 0;
1. }
Output:
Area of Rectangle is: 40
Structure using typedef:
typedef is a keyword that is used to assign a new name to any existing data-
type.
Example:
#include <iostream>
// Define a structure using typedef
typedef struct {
std::string name;
int age;
char gender;
} Person;
©Topperworld
C++ Programming
int main() {
// Declare a variable of the Person type
Person person1;
// Initialize the fields of the person1 variable
person1.name = "Alice";
person1.age = 30;
person1.gender = 'F';
// Display the information
std::cout << "Name: " << person1.name << std::endl;
std::cout << "Age: " << person1.age << std::endl;
std::cout << "Gender: " << person1.gender <<
std::endl;
return 0;
}
Output:
Name: Alice
Age: 30
Gender: F
©Topperworld
C++ Programming
❖ Difference between Structure and Class :
Structure Class
If access specifier is not declared If access specifier is not declared
explicitly, then by default access explicitly, then by default access
specifier will be public. specifier will be private.
Syntax of Structure: Syntax of Class:
struct structure_name class class_name
{ {
// body of the structure. // body of the class.
} }
The instance of the structure is known as The instance of the class is known as
"Structure variable". "Object of the class".
©Topperworld