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.

Bir yapıcı (constructor), bir nesne oluşturulduğunda otomatik olarak çalışan özel bir metottur. Bir yıkıcı (destructor) ise nesne yok edildiğinde çalışır.

Varsayılan yapıcı

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

Constructor overloading — birden fazla 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ı (Destructor) — nesne yok edildiğinde çalışır

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

Farklı kurucularla nesne oluşturma

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

Yapıcılar (Constructors), sınıf ile aynı ada sahiptir ve dönüş türleri yoktur. Yıkıcılar (Destructors) ~ClassName() kullanır ve nesneler kapsam dışına çıktığında, oluşturulma sırasının tersi yönde otomatik olarak çağrılırlar.

challenge icon

Görev

Orta

Üç aşırı yüklenmiş yapıcı (constructor) ve bir yıkıcıya (destructor) sahip bir Product sınıfı oluşturun:

  • 3 parametreli yapıcı: name, price, stock
  • 2 parametreli yapıcı: name, price (stock = 0)
  • Varsayılan yapıcı: 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