Menu
Coddy logo textTech

Ctor ve Dtor Temelleri

Coddy'nin C++ Journey'sinin Nesne Yönelimli Programlama bölümünün bir parçası. Ders 10 / 104.

Yapıcı, bir nesne oluşturulduğunda otomatik olarak çalışan özel bir yöntemdir. Yıkıcı, nesne yok edildiğinde çalışır.

Varsayılan kurucu

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

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

Parametreli kurucu

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

Yapıcı aşırı yükleme: birden çok yapıcı

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;
    }
};

Yıkıcı: nesne yok edildiğinde çalışır

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

Farklı yapıcılarla nesneler oluşturma

Book book1;                        // Varsayılan yapıcı
Book book2("Harry Potter");         // Bir parametre
Book book3("1984", 328);            // İki parametre

Kurucular, dönüş türü olmadan sınıfla aynı ada sahiptir. Yıkıcılar ~ClassName() kullanır ve nesneler kapsam dışına çıktığında oluşturulma sırasının tersiyle otomatik olarak çağrılır.

challenge icon

Görev

Orta

Üç aşırı yüklenmiş kurucuya ve bir yıkıcıya sahip bir Product sınıfı oluştur:

  • 3 parametreli kurucu: name, price, stock
  • 2 parametreli kurucu: name, price (stock = 0)
  • Varsayılan kurucu: name = "Unknown", price = 0, stock = 0
  • Yıkıcı: "Destroying: <name>" yazdırır

Kendin dene

#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 iconKendini test et

Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.

Nesne Yönelimli Programlama bölümündeki tüm dersler

Kendi başına pratik yap: Online C++ derleyicisi