Menu
CoddyTech

Dasar Ctor dan Dtor

Termasuk bagian Pemrograman Berorientasi Object dalam perjalanan C++ di Coddy. Pelajaran 10 dari 104.

Constructor adalah method khusus yang berjalan secara otomatis saat object dibuat. Destructor berjalan saat object dihancurkan.

Konstruktor default

class Book {
private:
    std::string title;
    int pages;

public:
    Book() {
        this->title = "Unknown";
        this->pages = 0;
    }
};

Konstruktor berparameter

Book(std::string title, int pages) {
    this->title = title;
    this->pages = pages;
}

Overloading constructor: beberapa constructor

class Book {
private:
    std::string title;
    int pages;

public:
    Book() {
        this->title = "Unknown";
        this->pages = 0;
    }
    
    Book(std::string title) {
        this->title = title;
        this->pages = 0;
    }
    
    Book(std::string title, int pages) {
        this->title = title;
        this->pages = pages;
    }
};

Destructor: dijalankan saat object dihancurkan

class Book {
public:
    ~Book() {
        std::cout << "Book destroyed" << std::endl;
    }
};

Membuat object dengan constructor yang berbeda

Book book1;                        // Konstruktor bawaan
Book book2("Harry Potter");         // Satu parameter
Book book3("1984", 328);            // Dua parameter

Constructor memiliki nama yang sama dengan class tanpa tipe pengembalian. Destructor menggunakan ~ClassName() dan dipanggil secara otomatis dalam urutan terbalik dari pembuatannya saat object keluar dari cakupan.

challenge icon

Tantangan

Sedang

Buat class Product dengan tiga constructor overload dan sebuah destructor:

  • Constructor dengan 3 parameter: name, price, stock
  • Constructor dengan 2 parameter: name, price (stock = 0)
  • Constructor default: name = "Unknown", price = 0, stock = 0
  • Destructor: mencetak "Destroying: <name>"

Coba sendiri

#include <iostream>
#include "Product.h"

int main() {
    std::string name;
    int price, stock;
    std::getline(std::cin, name);
    std::cin >> price >> stock;
    
    Product product1(name, price, stock);
    Product product2("Keyboard", 79);
    Product product3;
    
    std::cout << "Product 1: " << product1.getName() << " - $" << product1.getPrice() << " (Stock: " << product1.getStock() << ")" << std::endl;
    std::cout << "Product 2: " << product2.getName() << " - $" << product2.getPrice() << " (Stock: " << product2.getStock() << ")" << std::endl;
    std::cout << "Product 3: " << product3.getName() << " - $" << product3.getPrice() << " (Stock: " << product3.getStock() << ")" << std::endl;
    return 0;
}
quiz iconUji dirimu

Pelajaran ini berisi kuis singkat. Mulai pelajarannya untuk menjawab kuis dan melacak progresmu.

Semua pelajaran di Pemrograman Berorientasi Object

Latihan sendiri: Compiler C++ online