Hello, welcome back to the C++ learning tutorial.
In this tutorial, we will learn about the Struct data type in C++. This Struct data type is actually similar to Enum.
If you haven't learned Enum yet, I recommend learning it first. Please click the following link to learn it:
For those of you who have..
Let's start learning Struct .
What is a Struct?
A structure or struct is a collection of several variables with various data types wrapped in one variable.
In other programming languages, this struct can be likened to:
- Records in Pascal;
- Dictionary if in Python ;
- Associative Array in PHP ;
- Object if in Javascript language .
So, for programming languages that are still close to C, such as C++, we call it Struct .
Why do we need structs?
Now try to look at the following case example:
For example, we want to store student data. We could just do it like this:
string name = "Dian";
string address = "Mataram";
int age = 22;
So what if there is more than one student?
Maybe we could do it like this:
string name = "Dian";
string address = "Mataram";
int age = 22;
string name2 = "Bambang";
string address2 = "Surabaya";
int age2 = 23;
string name3 = "Bimo";
string address3 = "Jakarta";
int age3 = 23;
Ugh! doesn't look good.
So that we don't create a lot of variables like this, we can wrap the variables that are still in one group in a struct .
How to do?
Let's learn:
How to Create Structs
We can create structs with keywords struct
followed by the struct name and its contents.
Example:
struct Mahasiswa
{
string name;
string address;
int age;
};
In this example, we create a struct with a name Mahasiswa
in which there are three variables, namely name
, address
, and age
.
Apart from the method above, we can also create a Struct with the keyword typedef
. This keyword is for creating a new custom data type in C++.
For example:
typedef struct
{
string name;
string address;
int age;
} Mahasiswa;
If you use typedef
, then the Struct name is written at the end.
Actually it could also be in front like this:
typedef struct Mahasiswa
{
string name;
string address;
int age;
};
What's the difference between a Struct that uses one typedef
and one that doesn't?
The struct that uses typedef
it will be considered a data type and we can create instance variables without having to use struct
. BTW, this applies to C language. In C++, typedef
you can do without.
OK, now how do I use this struct?
How to Use Struct
In order for a struct to work, we must create a variable with the struct data type.
Example:
Mahasiswa mhs1;
In this example, we create a variable mhs1
with a data type Mahasiswa
where Mahasiswa
this data type is the name of the struct.
Then to fill the value into the variable mhs1
, we can call the name of the member variable from the struct.
Example:
mhs1.name = "Budi";
mhs1.address = "Jakarta";
mhs1.age = 22;
Or it can also be filled in directly when creating a variable, in this way:
Mahasiswa mhs1 = {
.name = "Budi",
.address = "Jakarta",
.age = 22
};
This method is called designated initializers .
BTW, this method can be done in the C++20
yes version. If you use C++ below C++20
this method will not work.
Another way, it could be like this:
Mahasiswa mhs1 = {"Budi", "Jakarta", 22};
So, this method is called Aggregate initialization 1 . Starting with version C++11
.
Then, which method should we use?
You're free to use any method, the most important thing is to adapt it to the version of C++ you are using.
Now let's try practice!
Practice: Using Structs in C++
Create a new program with a name latihan_struct.c
then fill it with the following code.
#include <iostream>
using namespace std;
// membuat struct
struct Mahasiswa {
string name;
string address;
int age;
};
int main(){
// menggunakan struct
Mahasiswa mhs1;
// mengisi nilai ke struct
mhs1.name = "Dian";
mhs1.address = "Mataram";
mhs1.age = 22;
Mahasiswa mhs2 = {"Bambang", "Surabaya", 23};
// mencetak isi struct
cout << "## Mahasiswa 1 ##\n";
cout << "Nama: " << mhs1.name << endl;
cout << "Alamat: " << mhs1.address << endl;
cout << "Umur: " << mhs1.age << endl;
cout << "## Mahasiswa 2 ##\n";
cout << "Nama: " << mhs2.name << endl;
cout << "Alamat: " << mhs2.address << endl;
cout << "Umur: " << mhs2.age << endl;
return 0;
}
The result:
Struct di dalam Struct (Nested Struct)
We can also create structs inside structs. This is called a Nested Struct or nested struct.
Example:
struct Weapon
{
string name;
int attackPower;
int range;
};
struct Player
{
string name;
int healthPoin;
Weapon weapon;
};
Then how to use it will be like this:
Player player1;
player1.name = "Petani Kode";
player1.healthPoin = 100;
player1.weapon.name = "Katana";
player1.weapon.attackPower = 30;
player1.weapon.range = 100;
Or it could be like this:
Player player1 = {
.name = "Petani Kode",
.healthPoin = 100, // 100%
.weapon = {
.name = "Katana",
.attackPower = 30,
.range = 100, // 1 meter
}
};
Or it could be like this:
Player player1 = { "Petani Kode", 100, {"Katana", 30, 100}};
Passing a Struct into a Function
We can create a struct as a parameter for a function.
Example:
#include <iostream>
using namespace std;
struct Student
{
string name;
int age;
};
int main() {
Student s1;
cout << "Enter name: ";
cin >> s1.name;
cout << "Enter age: ";
cin >> s1.age;
display(s1); // passing structure as an argument
return 0;
}
// membuat fungsi dengan struct sebagai parameter
void display(Student s) {
cout << "Displaying information\n";
cout << "Name: " << s.name << endl;
cout << "Age:" << s.age << endl;
}
The result:
Storing Functions in Struct
Apart from storing variables, it turns out we can also store functions in Structs.
For example:
struct Player {
string name;
int healthPoin;
void showPlayerStatus(){
cout << "Name: " << name << endl;
cout << "HP: " << healthPoin << endl;
}
};
Then the way to call it will be like this:
// membuat variabel untuk struct
Player p1;
// memanggil fungsi yang ada di dalam struct
p1.showPlayerStatus();
To understand better, let's try an exercise:
Create a new file with the name struct_fungsi.cpp
, then fill it with the following code:
#include <iostream>
using namespace std;
// mendefinisikan struct Player
struct Player {
string name;
int healthPoin;
// kita tambahkan fungsi di dalam struct ini
void showPlayerStatus() {
cout << "-- Player Status --\n";
cout << "Nama: " << name << endl;
cout << "HP: " << healthPoin << endl;
}
};
int main() {
// membuat dan mengisi nilai ke struct
Player p1 = {
.name = "Petani Kode",
.healthPoin = 100
};
// memanggil fungsi yang ada di dalam struct
p1.showPlayerStatus();
return 0;
}
In this example, we create a Player struct and inside it there is a function showPlayerStatus()
. This function will print the status of the Player.
Let's try to compile and run it.
So the result is:
If Structs can be filled with functions, then what's the difference with class
?
The struct is actually almost the same as class
. In OOP (Object Oriented Programming) , we have to create an object prototype first with class
. But actually it can also be done with Struct.
Well, the difference between Struct class
lies in the access rights of its members. By default, Structs can be accessed publicly. Meanwhile class
, we can set the members to public, private, and protected.
Oh yes, for those of you who don't understand the OOP concept. Maybe you will be confused in this part. But it doesn't matter, later when you understand OOP, try studying it again and you will immediately understand it.
Let's continue discussing:
Constructor and Destructor Functions in Struct
The Constructor function is a function that will be called when creating an object or variable from a struct. Meanwhile, the Destructor will be called when the variable or object is deleted.
The way to add constructor and destructor functions in Struct is the same as adding regular functions. But without a return type and the function name must be the same as the Struct name. For the destructor function, its name must be added ~
at the front.
Example:
struct Player {
string name;
int hp;
// fungsi constructor
Player(){ ... }
// fungsi destructor
~Player() { ... }
}
Take note..
In this example, there are two functions that we add to the struct Player
, namely function Player()
and ~Player()
.
Functions Player()
are constructors and ~Player()
are destructors. In these two functions we can fill in the commands to be carried out.
For example like this:
struct Player {
string name;
int hp;
Player(){
cout << "Object Player dibuat" << endl;
}
~Player() {
cout << "Object Player dihancurkan" << endl;
}
}
In this example, we display text with cout
the constructor Player()
and destructor functions ~Player()
. Later, when this struct is created the function Player()
will be called and when the variable is deleted, the function ~Player()
will be called.
To understand better, let's try an exercise:
Create a new program with a name struct_construct_destruct.cpp
then fill it with the following code:
#include <iostream>
using namespace std;
struct Player {
string name;
int healthPoin;
Player() { cout << "✨ Object dibuat!" << endl; }
~Player() { cout << "🔥 Object dihancurkan!" << endl; }
void showPlayerStatus() {
cout << "-- Player Status --\n";
cout << "Nama: " << name << endl;
cout << "HP: " << healthPoin << endl;
}
};
int main() {
Player p1;
p1.name = "Petani Kode";
p1.healthPoin = 100;
p1.showPlayerStatus();
return 0;
}
After that, compile and run.
So the result is:
Take a look!
On function main()
, we never call function Player()
and also ~Player()
. But why is this function run?
Yes, obviously, because he is a constructor and destructor. The function Player()
will be automatically called when we create a variable p1
.
Player p1;
Then the function ~Player()
will be automatically called when the variable p1
is deleted from memory. In the program above, the variable p1
will be automatically deleted after the function main()
has finished executing.
I hope you can understand this explanation.
What is next?
So far we have known and used Struct.
The main thing is:
The struct is used to store several related data in one variable. Apart from that, structs can also store functions like class
.
Furthermore:
Please learn about union data types.
If there is something you don't understand, please ask in the comments.
Happy learning!
Post a Comment