Menu
Coddy logo textTech

Grundlagen zu Ctors & Dtors

Teil des Abschnitts Objektorientierte Programmierung der C++-Journey von Coddy — Lektion 10 von 104.

Ein Konstruktor ist eine spezielle Methode, die automatisch ausgeführt wird, wenn ein Objekt erstellt wird. Ein Destruktor wird ausgeführt, wenn das Objekt zerstört wird.

Standardkonstruktor

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

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

Parametrisierter Konstruktor

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

Konstruktor-Überladung — mehrere Konstruktoren

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

Destruktor — wird ausgeführt, wenn das Objekt zerstört wird

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

Erstellen von Objekten mit verschiedenen Konstruktoren

Book book1;                        // Standardkonstruktor
Book book2("Harry Potter");         // Ein Parameter
Book book3("1984", 328);            // Zwei Parameter

Konstruktoren haben denselben Namen wie die Klasse und besitzen keinen Rückgabetyp. Destruktoren verwenden ~ClassName() und werden automatisch in umgekehrter Reihenfolge ihrer Erstellung aufgerufen, wenn Objekte den Gültigkeitsbereich verlassen.

challenge icon

Aufgabe

Mittel

Erstellen Sie eine Product-Klasse mit drei überladenen Konstruktoren und einem Destruktor:

  • 3-Parameter-Konstruktor: name, price, stock
  • 2-Parameter-Konstruktor: name, price (stock = 0)
  • Standardkonstruktor: name = "Unknown", price = 0, stock = 0
  • Destruktor: gibt "Destroying: <name>" aus

Probier es selbst

#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 iconTeste dich selbst

Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.

Alle Lektionen in Objektorientierte Programmierung