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

Überladen von Konstruktoren: 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;
    }
};

Objekte mit verschiedenen Konstruktoren erstellen

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

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

challenge icon

Aufgabe

Mittel

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

  • Konstruktor mit 3 Parametern: Name, Preis, Bestand
  • Konstruktor mit 2 Parametern: Name, Preis (Bestand = 0)
  • Standardkonstruktor: Name = "Unknown", Preis = 0, Bestand = 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

Übe selbstständig: Online-C++-Compiler