Skip to content
    SeaCode
    Learning tracksCode ArenaWorkshops & EventsInstructors
    Log inSign up
    C++C++

    C++ fundamentals

    • Your first C++ program
    • Variables and types
    • Operators and input
    • Conditions: if and switch
    • Loops

    Functions and collections

    • Functions
    • References: by value or by reference?
    • Strings and arrays
    • std::vector
    • map, set and unordered_map

    Memory and pointers

    • Pointers
    • Stack, heap, new and delete
    • Smart pointers and RAII

    Classes and OOP

    • struct and class
    • Constructors and destructors
    • Inheritance and virtual functions
    • Templates

    The STL and professional C++

    • Algorithms and lambdas
    • Exceptions
    • Recursion
    • Project: a grade book
    C++

    Classes and OOP · Lesson 15 of 21

    Constructors and destructors

    Initializer lists, when destructors run, and the rules of zero and three.

    11 minutes2 games

    A constructor is a function named after the class that runs when an object is created and sets it up. A destructor (~Name) runs when the object dies. The best way to give members their values is the initializer list after :.

    C++
    #include <iostream>
    #include <string>
    
    class Student {
    public:
        Student(std::string name, int level = 1)
            : name_(std::move(name)), level_(level) {
            std::cout << "hello " << name_ << "\n";
        }
        ~Student() { std::cout << "bye " << name_ << "\n"; }
    
        std::string describe() const { return name_ + " L" + std::to_string(level_); }
    
    private:
        std::string name_;
        int level_;
    };
    
    int main() {
        Student a("Laila", 3);
        {
            Student b("Omar");
            std::cout << b.describe() << "\n";
        }                                   // b dies here
        std::cout << a.describe() << "\n";
        return 0;
    }                                       // a dies here
    Step by step1 / 6
    1. ▶Student a("Laila", 3);
    2. 2{
    3. 3 Student b("Omar");
    4. 4 std::cout << b.describe();
    5. 5}
    6. 6std::cout << a.describe();
    7. 7return 0;

    Variables

    aLaila L3

    Output

    hello Laila

    Follow when each object is born and dies.

    Important

    Members are initialized in the order they're declared in the class, not the initializer list's order. A const or reference member must be set in the initializer list, because the constructor body runs after members already exist.

    The rule of zero and the rule of three

    If a class only uses self-managing members (std::string, std::vector, smart pointers), don't write a destructor, copy constructor or copy assignment: the compiler's versions are correct. That's the rule of zero.

    If a class manages a resource by hand (a pointer from new), the default copy copies just the pointer, leaving two objects that free the same memory. Then you must write all three (destructor, copy constructor, copy assignment), or more simply switch to unique_ptr or vector.

    What's the output?

    #include <iostream>
    struct A {
        char c;
        A(char x) : c(x) { std::cout << c; }
        ~A() { std::cout << (char)(c - 32); }
    };
    int main() {
        A x('a');
        A y('b');
        std::cout << "-";
    }

    What will this code print?

    Interview question

    Explain the rule of three (and of five, and of zero).

    Exercise

    Make a Box class whose constructor takes an int and prints + and the number, and whose destructor prints - and the number. In main create Box 1, then Box 2 inside a block. The output must be +1 +2 -2 -1 on one line.

    Expected output: +1 +2 -2 -1

    C++
    #include <iostream>
    
    class Box {
        
    };
    
    int main() {
        
        return 0;
    }

    Learn more from

    • learncpp: Constructor member initializer listslearncpp.com
    • cppreference: The rule of three/five/zeroen.cppreference.com
    • cppreference: Destructorsen.cppreference.com

    Played 0 of 2 games

    Sign in to save your progress and earn XP.

    Previousstruct and classNextInheritance and virtual functions
    SeaCode

    Learn to code for real, online or at our branch in front of Cairo University, Giza.

    Learn

    • All courses
    • Interactive tutorials
    • Interview practice problems
    • Mock interview
    • Learning tracks
    • Code Arena
    • Workshops & Events
    • Knowledge library
    • Team projects

    Your account

    • Log in
    • Sign up
    • Learning plan
    • Certificates
    • Site map

    Contact us

    • WhatsApp
    • 010 9094 1104
    • In front of Cairo University, Giza

    © 2026 SeaCode. All rights reserved.