Menu
Coddy logo textTech

Ctors & Dtors Basics

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 10 of 104.

A constructor is a special method that runs automatically when an object is created. A destructor runs when the object is destroyed.

Default constructor

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

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

Parameterized constructor

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

Constructor overloading — multiple constructors

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 — runs when object is destroyed

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

Creating objects with different constructors

Book book1;                        // Default constructor
Book book2("Harry Potter");         // One parameter
Book book3("1984", 328);            // Two parameters

Constructors have the same name as the class with no return type. Destructors use ~ClassName() and are called automatically in reverse order of creation when objects go out of scope.

challenge icon

Challenge

Medium

Create a Product class with three overloaded constructors and a destructor:

  • 3-parameter constructor: name, price, stock
  • 2-parameter constructor: name, price (stock = 0)
  • Default constructor: name = "Unknown", price = 0, stock = 0
  • Destructor: prints "Destroying: <name>"

Try it yourself

#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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming