Constructor adalah fungsi anggota khusus yang dieksekusi secara otomatis setiap kali sebuah objek kelas baru diinstansiasi.
Poin Kunci Materi:
- Nama Identik dengan Class: Tidak memiliki tipe return (bahkan bukan void).
- Member Initializer List (
: attr(val)): Cara tercepat dan terefisien untuk menginisialisasi atribut anggota objek. - Destructor (
~NamaClass): Dieksekusi otomatis saat siklus hidup objek berakhir, krusial untuk membebaskan koneksi file atau memori pointer.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
font-family: 'Fira Code', Consolas, Monaco, monospace;
background: #0f172a;
color: #f8fafc;
padding: 20px;
margin: 0;
line-height: 1.6;
}
.header {
background: #1e293b;
padding: 10px 16px;
border-radius: 8px 8px 0 0;
border-bottom: 2px solid #334155;
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: #94a3b8;
}
.dot { width: 12px; height: 12px; border-radius: 50%; display: inline-block; }
.dot-red { background: #ef4444; }
.dot-yellow { background: #eab308; }
.dot-green { background: #22c55e; }
.code-box {
background: #1e293b;
padding: 18px 20px;
border-bottom: 1px dashed #334155;
color: #38bdf8;
font-size: 14px;
white-space: pre-wrap;
}
.comment { color: #64748b; font-style: italic; }
.output-box {
background: #020617;
padding: 18px 20px;
border-radius: 0 0 8px 8px;
color: #e2e8f0;
font-size: 13px;
}
</style>
</head>
<body>
<div class="header">
<span class="dot dot-red"></span>
<span class="dot dot-yellow"></span>
<span class="dot dot-green"></span>
<span style="margin-left: 8px; font-weight: bold; color: #38bdf8;">⚙️ C++ Constructors - Skillance C++20</span>
</div>
<div class="code-box">
<span class="comment">// Skrip C++20 - Skillance Academy Indonesia</span>
#include <iostream>
#include <string>
class Buku {
public:
std::string judul;
int halaman;
// Parameterized Constructor dengan Member Initializer List
Buku(std::string j, int h) : judul(j), halaman(h) {
std::cout << ">> Constructor terpanggil untuk: " << judul << "\n";
}
// Destructor (dijalankan otomatis saat objek dihancurkan)
~Buku() {
std::cout << ">> Destructor menghapus objek: " << judul << "\n";
}
};
int main() {
{
Buku b1("Algoritma C++ Modern", 420);
std::cout << "Membaca " << b1.judul << " (" << b1.halaman << " hal)\n";
} // b1 keluar dari scope di sini, destructor langsung terpanggil
return 0;
}
</div>
<div class="output-box">
<div style="color: #64748b; margin-bottom: 6px;">[Terminal Output] > g++ -std=c++20 main.cpp -o main && ./main</div>
<div style="color: #4ade80; font-weight: bold;">>> Constructor terpanggil untuk: Algoritma C++ Modern<br>Membaca Algoritma C++ Modern (420 hal)<br>>> Destructor menghapus objek: Algoritma C++ Modern</div>
</div>
</body>
</html>
Coba Sendiri (Try it Yourself) »