LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 10 of 27

Constructors and Destructors

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Constructors and Destructors · Study material

Constructors and destructors in C++ control the beginning and the end of an object's life. A constructor runs automatically when an object is created and puts it into a valid state; a destructor runs automatically when the object is destroyed and releases what it owns. Around them C++ builds a whole toolkit: default, parameterized and delegating constructors, member initializer lists, explicit, the copy constructor and copy assignment, move constructor and move assignment, = default and = delete, and the rule of three, five and zero. Constructor and copy questions appear in nearly every C++ interview. This page explains all of it with programs you can run, followed by 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.

On this page

  • Default, parameterized and overloaded constructors
  • Member initializer lists, initialization order, delegating constructors
  • explicit and converting constructors
  • Copy constructor and copy assignment: shallow vs deep copy
  • Move constructor and move assignment, = default and = delete
  • Rule of three, five and zero; destructors, virtual destructors and order of destruction

What is a constructor?

A constructor is a special member function with the same name as the class and no return type – not even void. It is called automatically whenever an object is created: as a local variable, with new, as a member of another object or as an element of a container. Constructors can be overloaded, so a class may offer several ways to be created.

#include <iostream>
#include <string>

class Rectangle {
    double w_, h_;
public:
    Rectangle() : w_(1), h_(1) { std::cout << "default "; }                      // default constructor
    Rectangle(double side) : w_(side), h_(side) { std::cout << "square "; }      // one parameter
    Rectangle(double w, double h) : w_(w), h_(h) { std::cout << "rect "; }       // two parameters
    Rectangle(const Rectangle& o) : w_(o.w_), h_(o.h_) { std::cout << "copy "; } // copy constructor
    double area() const { return w_ * h_; }
};

int main() {
    Rectangle a;            // default
    Rectangle b(4);         // square
    Rectangle c{3, 5};      // rect
    Rectangle d = c;        // copy
    std::cout << '\n' << a.area() << ' ' << b.area() << ' ' << c.area() << ' ' << d.area() << '\n';
    return 0;
}

Output

default square rect copy
1 16 15 15
ConstructorSignatureCalled for
DefaultT()T a;, T a{};, arrays, containers
ParameterizedT(int, double)T a(1, 2.0);, T a{1, 2.0};
CopyT(const T&)T b = a;, pass/return by value
MoveT(T&&) noexceptT b = std::move(a);, temporaries
ConvertingT(U) (not explicit)implicit U → T conversions
initializer_listT(std::initializer_list<U>)T a{1, 2, 3};

If you declare no constructor at all, the compiler provides a default constructor. As soon as you declare any constructor, the implicit default constructor disappears – write T() = default; to get it back.

The member initializer list

After the parameter list, a colon introduces the member initializer list: : id_(id), name_(name). Members listed there are initialized directly; assignments in the constructor body happen only after every member has already been default-constructed. The list is required for const members, reference members, members without a default constructor, and base classes.

#include <iostream>
#include <string>

class Employee {
    const int id_;                 // const member: must be initialized, cannot be assigned
    std::string& team_;            // reference member: must be bound in the initializer list
    std::string name_;
    double salary_ = 30000;        // default member initializer
public:
    Employee(int id, std::string& team, std::string name)
        : id_(id), team_(team), name_(std::move(name)) {}   // initializes, rather than assigning later
    void show() const { std::cout << id_ << ' ' << name_ << ' ' << team_ << ' ' << salary_ << '\n'; }
};

int main() {
    std::string team = "Platform";
    Employee e(101, team, "Asha");
    team = "Data";                 // e.team_ refers to the same string
    e.show();
    return 0;
}

Output

101 Asha Data 30000

Initialization order

Members are always initialized in the order they are declared in the class, never in the order written in the initializer list (compilers warn with -Wreorder). Base classes come before members. Never initialize one member from another that is declared later.

#include <iostream>

struct Tag {
    explicit Tag(const char* n) { std::cout << n << ' '; }
};

class Widget {
    Tag first_;                    // members are initialized in DECLARATION order…
    Tag second_;
public:
    Widget() : second_("second"), first_("first") {   // …not in the order written here
        std::cout << "body\n";
    }
};

int main() {
    Widget w;
    return 0;
}

Output

first second body

Delegating constructors

Since C++11 a constructor can call another constructor of the same class in its initializer list, so validation and set-up code is written once. A delegating constructor cannot initialize members itself; the target constructor runs completely first, then the delegating constructor's body.

#include <iostream>
#include <string>

class Account {
    std::string owner_;
    double balance_;
    std::string type_;
public:
    Account(std::string owner, double balance, std::string type)          // the one real constructor
        : owner_(std::move(owner)), balance_(balance), type_(std::move(type)) {
        std::cout << "[main ctor] ";
    }
    Account(std::string owner, double balance) : Account(std::move(owner), balance, "savings") {
        std::cout << "[2-arg] ";
    }
    explicit Account(std::string owner) : Account(std::move(owner), 0) { std::cout << "[1-arg] "; }
    void show() const { std::cout << owner_ << ' ' << balance_ << ' ' << type_ << '\n'; }
};

int main() {
    Account a("Asha");
    a.show();
    Account b("Ravi", 5000, "current");
    b.show();
    return 0;
}

Output

[main ctor] [2-arg] [1-arg] Asha 0 savings
[main ctor] Ravi 5000 current

explicit and converting constructors

A constructor that can be called with one argument also acts as an implicit conversion. That is convenient for types like a Celsius temperature, but dangerous for types like Meters or a container size: show_len(5) silently creating a Meters is rarely intended. Mark such constructors explicit. Most single-argument constructors should be explicit.

#include <iostream>

class Celsius {
    double v_;
public:
    Celsius(double v) : v_(v) {}               // converting constructor: double → Celsius implicitly
    double value() const { return v_; }
};

class Meters {
    double v_;
public:
    explicit Meters(double v) : v_(v) {}       // explicit: no silent conversions
    double value() const { return v_; }
};

void show_temp(Celsius c) { std::cout << c.value() << "C "; }
void show_len(Meters m)   { std::cout << m.value() << "m "; }

int main() {
    show_temp(36.6);              // OK: implicit conversion
    show_len(Meters(5));          // explicit construction required
    // show_len(5);               error: Meters(double) is explicit
    Celsius c = 25;               // copy-initialization uses the converting constructor
    std::cout << c.value() << '\n';
    return 0;
}

Output

36.6C 5m 25

Copying: copy constructor and copy assignment

The copy constructor creates a new object from an existing one (T b = a;); copy assignment replaces the contents of an existing object (b = a;). The compiler-generated versions copy each member – a shallow copy. For members that are raw owning pointers that is wrong: both objects would point to the same memory and both destructors would delete it. Such classes need a deep copy that allocates new memory.

#include <algorithm>
#include <cstring>
#include <iostream>

class Buffer {
    char* data_;
    std::size_t size_;
public:
    explicit Buffer(const char* s) : data_(new char[std::strlen(s) + 1]), size_(std::strlen(s)) {
        std::strcpy(data_, s);
    }
    Buffer(const Buffer& o) : data_(new char[o.size_ + 1]), size_(o.size_) {   // deep copy
        std::strcpy(data_, o.data_);
    }
    Buffer& operator=(const Buffer& o) {                                       // copy assignment
        if (this != &o) {                                                      // self-assignment check
            char* fresh = new char[o.size_ + 1];
            std::strcpy(fresh, o.data_);
            delete[] data_;
            data_ = fresh;
            size_ = o.size_;
        }
        return *this;
    }
    ~Buffer() { delete[] data_; }                                              // destructor
    void set(std::size_t i, char c) { data_[i] = c; }
    const char* c_str() const { return data_; }
};

int main() {
    Buffer a("hello");
    Buffer b = a;          // copy constructor: b gets its own memory
    Buffer c("x");
    c = a;                 // copy assignment
    b.set(0, 'j');
    c.set(0, 'c');
    std::cout << a.c_str() << ' ' << b.c_str() << ' ' << c.c_str() << '\n';
    return 0;
}

Output

hello jello cello

Moving: move constructor and move assignment

When the source is a temporary or has been cast with std::move, a move constructor can steal its resources instead of copying them and leave the source empty but valid. Mark move operations noexcept: std::vector moves elements during reallocation only if the move constructor cannot throw; otherwise it copies them.

#include <iostream>
#include <utility>

class Blob {
    int* data_;
    std::size_t n_;
public:
    explicit Blob(std::size_t n) : data_(new int[n]{}), n_(n) {}
    Blob(const Blob& o) : data_(new int[o.n_]), n_(o.n_) {
        std::copy(o.data_, o.data_ + n_, data_);
        std::cout << "copy ";
    }
    Blob(Blob&& o) noexcept : data_(o.data_), n_(o.n_) {      // steal the buffer
        o.data_ = nullptr;
        o.n_ = 0;
        std::cout << "move ";
    }
    Blob& operator=(Blob&& o) noexcept {
        if (this != &o) {
            delete[] data_;
            data_ = std::exchange(o.data_, nullptr);
            n_ = std::exchange(o.n_, 0);
        }
        std::cout << "move= ";
        return *this;
    }
    ~Blob() { delete[] data_; }
    std::size_t size() const { return n_; }
};

int main() {
    Blob a(1000);
    Blob b = a;                 // copy: allocates and copies 1000 ints
    Blob c = std::move(a);      // move: just takes the pointer
    Blob d(5);
    d = std::move(b);
    std::cout << '\n' << a.size() << ' ' << b.size() << ' ' << c.size() << ' ' << d.size() << '\n';
    return 0;
}

Output

copy move move=
0 0 1000 1000

The rule of three, five and zero

RuleStatement
Rule of threeif a class needs a custom destructor, copy constructor or copy assignment, it almost certainly needs all three
Rule of fivewith move semantics, add the move constructor and move assignment – five special members in total
Rule of zerobest of all: hold resources in members that manage themselves (std::string, std::vector, std::unique_ptr), and write none of the five

= default asks for the compiler-generated version; = delete forbids a function – for example copying of a class that must have exactly one owner.

#include <iostream>
#include <memory>
#include <string>
#include <vector>

class Course {                                 // rule of zero: members manage themselves
    std::string title_;
    std::vector<std::string> students_;
public:
    explicit Course(std::string t) : title_(std::move(t)) {}
    void enrol(std::string s) { students_.push_back(std::move(s)); }
    std::size_t count() const { return students_.size(); }
};                                             // copy, move and destructor generated correctly

class Connection {
    std::unique_ptr<int> handle_ = std::make_unique<int>(7);
public:
    Connection() = default;                    // ask for the compiler-generated version
    Connection(const Connection&) = delete;    // forbid copying: one owner per connection
    Connection& operator=(const Connection&) = delete;
    Connection(Connection&&) = default;        // moving is fine
    int handle() const { return handle_ ? *handle_ : -1; }
};

int main() {
    Course a("C++");
    a.enrol("Asha");
    Course b = a;                              // deep copy for free
    b.enrol("Ravi");
    std::cout << a.count() << ' ' << b.count() << '\n';

    Connection c1;
    Connection c2 = std::move(c1);             // allowed; Connection c3 = c2; would not compile
    std::cout << c1.handle() << ' ' << c2.handle() << '\n';
    return 0;
}

Output

1 2
-1 7

Destructors

A destructor is named ~ClassName, takes no parameters, returns nothing and cannot be overloaded. It runs automatically when an automatic object leaves its scope, when delete is called, when a container removes an element, and for temporaries at the end of the full expression. Destructors should not throw (they are noexcept by default).

Order: objects are destroyed in reverse order of construction. Inside one object, the destructor body runs first, then members in reverse declaration order, then base classes. A base class used polymorphically needs a virtual destructor, so that delete base_ptr runs the derived destructor too.

#include <iostream>

struct Part {
    char c;
    explicit Part(char x) : c(x) { std::cout << c; }
    ~Part() { std::cout << static_cast<char>(c - 32); }
};

struct Base {
    Part p{'b'};
    Base() { std::cout << "[Base]"; }
    virtual ~Base() { std::cout << "[~Base]"; }
};

struct Derived : Base {
    Part q{'d'};
    Part r{'e'};
    Derived() { std::cout << "[Derived]"; }
    ~Derived() override { std::cout << "[~Derived]"; }
};

int main() {
    Base* p = new Derived;      // build: base members, base body, derived members, derived body
    std::cout << '\n';
    delete p;                   // virtual destructor: reverse order, starting from Derived
    std::cout << '\n';
    return 0;
}

Output

b[Base]de[Derived]
[~Derived]ED[~Base]B

Temporaries and copy elision

Since C++17, initializing an object from a prvalue of the same type – T t = T(5); or return T(5); – constructs the object directly, with no copy or move at all (guaranteed copy elision). Returning a named local variable is usually optimised the same way (NRVO), but that is not guaranteed, so a move constructor is still useful. Temporaries live until the end of the full expression that created them.

Common mistakes

  • Assigning in the constructor body instead of initializing in the initializer list.
  • Relying on initializer-list order – declaration order decides.
  • Raw owning pointers with the default copy – double delete; follow the rule of three/five or use smart pointers.
  • Forgetting the self-assignment check (or copy-and-swap) in copy assignment.
  • Missing noexcept on move operations – containers fall back to copying.
  • Implicit single-argument constructors causing surprising conversions – use explicit.
  • Non-virtual destructor in a polymorphic base class.

Key points to remember

  • Constructors have the class name and no return type; destructors are ~Name() with no parameters.
  • Initialize members in the initializer list; they are built in declaration order.
  • Declaring any constructor removes the implicit default constructor.
  • Copy: deep for owned resources; move: steal and leave the source empty; mark moves noexcept.
  • Prefer the rule of zero; otherwise implement all five special members.
  • Destruction runs in reverse order; polymorphic bases need virtual destructors.

Frequently asked questions

What is the difference between the copy constructor and the assignment operator?

The copy constructor creates a new object (T b = a;). Copy assignment overwrites an object that already exists (b = a;), so it must also release the old contents and handle self-assignment.

Can a constructor be virtual?

No. When a constructor runs, the object's dynamic type is not yet known, so virtual dispatch makes no sense. Use a virtual clone() function or a factory instead. Destructors, however, can and often should be virtual.

Can a constructor call a virtual function?

It can, but the call is not dispatched to derived classes – during the base constructor the object is still treated as a base object.

Where can I learn more?

Read C++ Classes and Objects and C++ Move Semantics, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links