In the Classes & Objects topic, our BankAccount objects started life with default member initializers, and then we called setOwner() and deposit() to put real values in. That works, but it has a weakness: between creating the object and calling the setters, the object exists in a half-ready state, and nothing forces anyone to call the setters at all.
C++ solves this with two special member functions. A constructor runs automatically the moment an object is created, so the object is valid from its very first instant. A destructor runs automatically the moment an object dies, so it can clean up whatever the object was holding. Together they give C++ one of its most powerful ideas, RAII, which we promised in the Dynamic Memory Allocation topic.
In this topic we'll cover default and parameterized constructors, member initializer lists, delegating and explicit constructors, destructors and object lifetimes, the copy constructor, shallow vs deep copies, and the Rule of Three / Five / Zero.
What Is a Constructor?
A constructor is a special member function that has the same name as the class, has no return type (not even
void), and is called automatically when an object of the class is created. Its job is to put the new object into a valid state.
A destructor is a special member function named
~ClassName, with no parameters and no return type, that is called automatically when an object's lifetime ends. Its job is to release whatever the object owns.
A class can have many constructors (they can be overloaded, just like the functions in the Function Overloading topic), but exactly one destructor.
Default and Parameterized Constructors
A default constructor is one that can be called with no arguments.
A parameterized constructor takes arguments, so each object can start with its own values.
#include <iostream>
#include <string>
class Student
{
private:
std::string name;
int marks;
public:
Student() // default constructor
{
name = "Unknown";
marks = 0;
std::cout << "Default constructor: " << name << '\n';
}
Student(std::string n, int m) // parameterized constructor
{
name = n;
marks = (m >= 0 && m <= 100) ? m : 0; // validate once, here
std::cout << "Parameterized constructor: " << name << '\n';
}
~Student() // destructor
{
std::cout << "Destructor: " << name << '\n';
}
void show() const
{
std::cout << name << " scored " << marks << '\n';
}
};
int main()
{
std::cout << "--- start of main ---\n";
Student a; // calls Student()
Student b("Asha", 91); // calls Student(std::string, int)
Student c{"Ravi", 150}; // brace syntax works too; 150 is rejected
a.show();
b.show();
c.show();
std::cout << "--- end of main ---\n";
return 0;
} // destructors run here: c, b, a
Output:
--- start of main ---
Default constructor: Unknown
Parameterized constructor: Asha
Parameterized constructor: Ravi
Unknown scored 0
Asha scored 91
Ravi scored 0
--- end of main ---
Destructor: Ravi
Destructor: Asha
Destructor: Unknown
Let's trace it:
Student a;creates an object with no arguments, so the default constructor runs.Student b("Asha", 91);has two arguments, so overload resolution picksStudent(std::string, int).Student c{"Ravi", 150};uses braces (C++11 uniform initialization) and calls the same constructor. The constructor validates the marks, so the invalid 150 never gets stored. EveryStudentobject is guaranteed to have marks between 0 and 100, because the only way to create one is through a constructor.When
main()ends, the three objects go out of scope and their destructors run in reverse order of construction:c, thenb, thena. Objects built later may depend on objects built earlier, so they are torn down first, like plates stacked on top of each other.
We never call a constructor or destructor ourselves. The compiler inserts the calls at exactly the right places.
When Does the Compiler Give Us a Default Constructor?
If a class declares no constructors at all, the compiler generates a default constructor for us (that's why the classes in Classes & Objects could be created with BankAccount acc1;). But as soon as we declare any constructor, that free default constructor disappears:
#include <string>
class Student
{
private:
std::string name;
int marks;
public:
Student(const std::string& n, int m) : name(n), marks(m) {}
};
int main()
{
Student a("Asha", 91); // OK
Student b; // error: no default constructor
return 0;
}
g++ 15 rejects it (trimmed):
main.cpp:16:13: error: no matching function for call to ‘Student::Student()’
16 | Student b; // error: no default constructor
| ^
note: candidate 1: ‘Student::Student(const std::string&, int)’
note: candidate expects 2 arguments, 0 provided
If we still want Student b; to work, we have three options: write a default constructor ourselves, give every parameter a default argument (Student(const std::string& n = "Unknown", int m = 0), from the Default Arguments & Inline Functions topic), or ask the compiler to generate one with Student() = default; (C++11).
The implicitly generated default constructor default-initializes each member: class-type members such as std::string run their own default constructors, members with a default member initializer get that value, and plain int/double/pointer members are left uninitialized (garbage) for a local object.
| Point | Constructor | Ordinary member function |
|---|---|---|
| Name | Same as the class | Any name |
| Return type | None, not even void | Must have one |
| Called | Automatically, once, when the object is created | Explicitly, any number of times |
| Can be overloaded? | Yes | Yes |
Can be const? | No | Yes |
Can be virtual? | No | Yes |
Member Initializer Lists
In the Student example, the constructor body assigned values: name = n;. That's actually a two-step process. Before the body even starts, every member has already been created (name as an empty string); the body then overwrites it. For a std::string that's a wasted step. For some members, it's impossible.
A member initializer list is written after the constructor's parameter list, starting with a colon. It initializes each listed member directly with the given value, before the constructor body runs.
Student(const std::string& n, int m) : name(n), marks(m)
{
// body: all members already initialized here
}
Some members must be initialized in the list, because they can't be assigned later:
constdata members (a constant can't be assigned to).Reference members (a reference must be bound when it's created, as we saw in the References topic).
Members of a class type that has no default constructor.
Base classes that need arguments (we'll see this in Inheritance).
#include <iostream>
#include <string>
class Employee
{
private:
const int id; // const member: must be initialized, cannot be assigned
std::string& dept; // reference member: must be bound at creation
std::string name;
double salary;
public:
Employee(int i, std::string& d, const std::string& n, double s)
: id(i), dept(d), name(n), salary(s) // member initializer list
{
// body runs AFTER all members are initialized
if (salary < 0)
salary = 0;
}
void show() const
{
std::cout << id << " " << name << " (" << dept << ") Rs. " << salary << '\n';
}
};
int main()
{
std::string sales = "Sales";
Employee e1(1, sales, "Kiran", 52000);
Employee e2(2, sales, "Divya", -10);
e1.show();
e2.show();
sales = "Marketing"; // both employees refer to the same string
e1.show();
return 0;
}
Output:
1 Kiran (Sales) Rs. 52000
2 Divya (Sales) Rs. 0
1 Kiran (Marketing) Rs. 52000
id is const and dept is a reference, so writing id = i; or dept = d; in the constructor body would not compile. In the list they are initialized, which is allowed. Notice also that both employees' dept refer to the same string sales, so changing sales changes what e1.show() prints. (A reference member also means the object can't be assigned with = later, so use reference members sparingly.)
Rule of thumb: initialize members in the initializer list (or with default member initializers), and use the constructor body only for extra work such as validation or logging.
Initialization Order Follows Declaration Order
Here's a trap that appears in interviews. Members are initialized in the order they are declared in the class, not in the order you write them in the initializer list.
#include <iostream>
class Range
{
private:
int low; // declared 1st, initialized 1st
int high; // declared 2nd, initialized 2nd
int width; // declared 3rd, initialized 3rd
public:
Range(int l, int h) : low(l), high(h), width(high - low) {} // OK: low, high already set
void show() const
{
std::cout << "[" << low << ", " << high << "] width " << width << '\n';
}
};
int main()
{
Range r(10, 25);
r.show();
return 0;
}
Output:
[10, 25] width 15
This works because low and high are declared before width, so they already hold values when width(high - low) runs. Now move width to the top of the class:
class Broken
{
private:
int width; // declared FIRST, so initialized FIRST
int low;
int high;
public:
Broken(int l, int h) : low(l), high(h), width(high - low) {} // reads high and low too early!
};
The initializer list looks identical, but now width is initialized first, while high and low are still uninitialized. Reading them is undefined behavior, so width could hold any value. Luckily, -Wall catches this (trimmed):
warning: ‘Broken::high’ will be initialized after [-Wreorder]
warning: ‘int Broken::width’ [-Wreorder]
warning: when initialized here [-Wreorder]
warning: member ‘Broken::high’ is used uninitialized [-Wuninitialized]
warning: member ‘Broken::low’ is used uninitialized [-Wuninitialized]
Habit: always write the initializer list in the same order as the member declarations, and never let one member's initializer depend on a member declared after it.
Delegating Constructors, explicit and = default
When a class has several constructors, they often repeat the same setup code. Since C++11, one constructor can delegate to another by naming it in its initializer list.
#include <iostream>
class Time
{
private:
int h = 0, m = 0, s = 0;
public:
Time() = default; // explicitly ask for the default constructor
Time(int hh, int mm, int ss) : h(hh), m(mm), s(ss)
{
std::cout << " main constructor\n";
}
Time(int hh, int mm) : Time(hh, mm, 0) // delegating constructor (C++11)
{
std::cout << " (h, m) constructor\n";
}
explicit Time(int totalSeconds) // explicit: no silent int -> Time conversion
: Time(totalSeconds / 3600, totalSeconds / 60 % 60, totalSeconds % 60)
{
std::cout << " seconds constructor\n";
}
void show() const
{
std::cout << " " << h << "h " << m << "m " << s << "s\n";
}
};
void printTime(const Time& t)
{
t.show();
}
int main()
{
std::cout << "t1:\n";
Time t1;
t1.show();
std::cout << "t2:\n";
Time t2(9, 30);
t2.show();
std::cout << "t3:\n";
Time t3(3725);
t3.show();
// printTime(5000); // error: constructor is explicit
std::cout << "explicit call:\n";
printTime(Time(5000)); // OK: conversion written out
return 0;
}
Output:
t1:
0h 0m 0s
t2:
main constructor
(h, m) constructor
9h 30m 0s
t3:
main constructor
seconds constructor
1h 2m 5s
explicit call:
main constructor
seconds constructor
1h 23m 20s
Three features appear here:
Time() = default;(C++11) asks the compiler for its default constructor even though we wrote other constructors. The members get their default member initializers (0), and nothing is printed.Delegating constructors (C++11).
Time(int hh, int mm) : Time(hh, mm, 0)first runs the three-argument "main" constructor completely, and only then runs its own body. That's why "main constructor" is printed before "(h, m) constructor". A delegating constructor's initializer list must contain only the delegation, no other members.explicit. A constructor callable with one argument also acts as an implicit conversion: withoutexplicit,printTime(5000)would silently create aTimefrom theint5000, which is almost certainly a bug. Withexplicit, g++ rejects it:
error: invalid initialization of reference of type ‘const Time&’ from expression of type ‘int’
The C++ Core Guidelines recommend marking single-argument constructors explicit by default, unless the conversion is truly natural (for example, std::string from const char*).
Destructors and Object Lifetime
Rules for destructors:
Named
~ClassName, no parameters, no return type, so it can't be overloaded: one per class.If we don't write one, the compiler generates one that destroys the members (in reverse declaration order).
Destructors are implicitly
noexcept(C++11) unless you, or a member's or base class's destructor, explicitly say otherwise: they should never let an exception escape.Calling it is the compiler's job. Calling
obj.~ClassName()by hand on a normal object leads to a double destruction later, which is undefined behavior.
Exactly when the destructor runs depends on the object's storage duration. This program traces every kind:
#include <iostream>
#include <string>
class Tracer
{
private:
std::string label;
public:
explicit Tracer(const std::string& l) : label(l) { std::cout << " + " << label << '\n'; }
~Tracer() { std::cout << " - " << label << '\n'; }
};
Tracer globalObj("global"); // created before main() starts
void f()
{
static Tracer onlyOnce("static local"); // created on first call, destroyed after main()
Tracer local("local in f");
}
int main()
{
std::cout << "main starts\n";
Tracer m("main local");
{
Tracer inner("inner block");
std::cout << " leaving inner block\n";
} // inner destroyed here
f();
f(); // static local is NOT created again
Tracer* heap = new Tracer("heap");
delete heap; // destroyed exactly when we say
std::cout << "main ends\n";
return 0;
}
Output:
+ global
main starts
+ main local
+ inner block
leaving inner block
- inner block
+ static local
+ local in f
- local in f
+ local in f
- local in f
+ heap
- heap
main ends
- main local
- static local
- global
| Kind of object | Constructed | Destroyed |
|---|---|---|
| Global / namespace-scope | Before main() starts | After main() returns, in reverse order |
| Local (automatic) | When execution reaches its definition | At the closing } of its block, in reverse order |
static local | The first time execution reaches it (only once) | After main() returns |
Heap (new) | At new | Only at delete (never, if we forget) |
| Array elements | In index order, 0 first | In reverse index order |
Notice in the output that "static local" is created on the first call to f() only, survives both calls, and is destroyed after main() ends but before "global", because static-storage objects die in the reverse order of their construction.
RAII: Resource Acquisition Is Initialization
Since the destructor runs automatically whenever an object goes out of scope, we can tie a resource (heap memory, an open file, a network connection, a lock) to an object:
RAII means: acquire the resource in the constructor, release it in the destructor. The resource's lifetime then equals the object's lifetime, so it can never be forgotten.
#include <iostream>
#include <string>
// A tiny RAII class: "acquires" in the constructor, "releases" in the destructor
class Connection
{
private:
std::string server;
public:
explicit Connection(const std::string& s) : server(s)
{
std::cout << " open connection to " << server << '\n';
}
~Connection()
{
std::cout << " close connection to " << server << '\n';
}
void send(const std::string& msg) const
{
std::cout << " send '" << msg << "' to " << server << '\n';
}
};
bool upload(int fileSize)
{
Connection c("backup-server"); // resource acquired
if (fileSize <= 0)
{
std::cout << " invalid size, returning early\n";
return false; // destructor still runs
}
c.send("file of " + std::to_string(fileSize) + " KB");
return true;
} // destructor runs here on the normal path
int main()
{
std::cout << "upload(0):\n";
upload(0);
std::cout << "upload(250):\n";
upload(250);
return 0;
}
Output:
upload(0):
open connection to backup-server
invalid size, returning early
close connection to backup-server
upload(250):
open connection to backup-server
send 'file of 250 KB' to backup-server
close connection to backup-server
The function has two exit paths, yet we wrote the cleanup code only once, and it ran on both. With a manual "close" call, every return (and every exception, see Exception Handling) would need its own copy, and one day someone would forget. This is exactly how std::vector, std::string, file streams and smart pointers manage their resources.
The Copy Constructor
A copy constructor creates a new object as a copy of an existing object of the same class. Its usual form is
ClassName(const ClassName& other).
If we don't write one, the compiler generates one that copies each member in turn (a memberwise copy). Let's write our own that prints a message, so we can see exactly when copies happen:
#include <iostream>
#include <string>
class Book
{
private:
std::string title;
public:
Book(const std::string& t) : title(t)
{
std::cout << " constructor: " << title << '\n';
}
Book(const Book& other) : title(other.title + " (copy)") // copy constructor
{
std::cout << " copy constructor: " << title << '\n';
}
~Book()
{
std::cout << " destructor: " << title << '\n';
}
};
void byValue(Book) // parameter is copy-initialized from the argument
{
std::cout << " inside byValue\n";
}
void byReference(const Book&) // no copy
{
std::cout << " inside byReference\n";
}
Book make()
{
return Book("Fresh"); // C++17: guaranteed copy elision, no copy
}
int main()
{
std::cout << "1. Book a(\"C++\")\n";
Book a("C++");
std::cout << "2. Book b = a\n";
Book b = a;
std::cout << "3. byValue(a)\n";
byValue(a);
std::cout << "4. byReference(a)\n";
byReference(a);
std::cout << "5. Book c = make()\n";
Book c = make();
std::cout << "6. end of main\n";
return 0;
}
Output:
1. Book a("C++")
constructor: C++
2. Book b = a
copy constructor: C++ (copy)
3. byValue(a)
copy constructor: C++ (copy)
inside byValue
destructor: C++ (copy)
4. byReference(a)
inside byReference
5. Book c = make()
constructor: Fresh
6. end of main
destructor: Fresh
destructor: C++ (copy)
destructor: C++
The copy constructor runs when:
An object is initialized from another object:
Book b = a;orBook b(a);orBook b{a};.An object is passed by value: the parameter is a new object copied from the argument. It's destroyed when the function finishes.
An object is returned by value, unless the copy is elided. In step 5,
return Book("Fresh");returns a temporary, and since C++17 the compiler is required to build it directly inc(guaranteed copy elision), so no copy constructor runs. For returning a named local variable (Book x("Fresh"); return x;), the elision (called NRVO) is allowed but not guaranteed.
Passing by const& (step 4) makes no copy at all, which is why it's the normal way to pass objects.
Also note: Book b = a; is initialization (copy constructor), even though it contains =. Only b = a; on an already existing b is assignment, which uses a different function, the copy assignment operator, which we'll meet below.
Why Must the Parameter Be a Reference?
Suppose we wrote Book(Book other). To call it, the argument must be copied into other, which needs the copy constructor, which needs a copy for its parameter, and so on forever. C++ doesn't allow it at all; g++ says:
error: invalid constructor; you probably meant ‘Book (const Book&)’
The parameter is const so that we can copy from const objects and temporaries, and to promise that copying doesn't modify the original.
Shallow Copy vs Deep Copy
The compiler's memberwise copy is perfect for members like int and std::string. But when a class holds a raw pointer to memory it owns, copying the pointer is a disaster.
#include <iostream>
class IntArray
{
private:
int* data;
int size;
public:
explicit IntArray(int n) : data(new int[n]{}), size(n) {} // acquire in constructor
~IntArray() { delete[] data; } // release in destructor
// No copy constructor written: the compiler generates one
// that copies the POINTER, not the elements (a shallow copy).
void set(int i, int v) { data[i] = v; }
int get(int i) const { return data[i]; }
};
int main()
{
IntArray a(3);
a.set(0, 10);
IntArray b = a; // shallow copy: b.data == a.data
b.set(0, 99); // also changes a!
std::cout << "a[0] = " << a.get(0) << '\n';
return 0;
} // b's destructor frees the block, then a's frees it AGAIN
What we see in a terminal (g++ 15 on Linux, normal build; the last line comes from the shell):
a[0] = 99
free(): double free detected in tcache 2
Aborted (core dumped)
Two problems, both caused by the generated copy constructor copying only the pointer (a shallow copy):
a.data ──┐
├──► [ 99 | 0 | 0 ] one heap block, two owners
b.data ──┘
Shared data: changing
balso changeda, soa[0]printed 99.Double delete: at the end of
main(),b's destructor frees the block, thena's destructor frees the same block again. That is undefined behavior (the Dynamic Memory Allocation topic's "double delete"). Here glibc happened to detect it and abort; with-fsanitize=addresswe get the full story (trimmed):
a[0] = 99
==1134==ERROR: AddressSanitizer: attempting double-free on 0x702fd81e0010 in thread T0:
#1 ... in IntArray::~IntArray() main.cpp:11
freed by thread T0 here:
#1 ... in IntArray::~IntArray() main.cpp:11
previously allocated by thread T0 here:
#1 ... in IntArray::IntArray(int) main.cpp:10
The fix is a deep copy: the new object allocates its own block and copies the elements into it.
a.data ──► [ 10 | 0 | 0 ]
b.data ──► [ 99 | 0 | 0 ] separate blocks, one owner each
The Rule of Three
A deep copy constructor alone is not enough. Assignment (c = a;) between two existing objects also copies, and the compiler-generated copy assignment operator is shallow too. Hence the classic rule:
Rule of Three: if a class needs a user-written destructor, copy constructor or copy assignment operator, it almost certainly needs all three.
The reason is always the same: the class owns a resource that the compiler doesn't know how to copy or release.
#include <iostream>
#include <algorithm> // std::copy
class IntArray
{
private:
int* data;
int size;
public:
explicit IntArray(int n) : data(new int[n]{}), size(n)
{
std::cout << " construct (size " << size << ")\n";
}
// 1. Destructor
~IntArray()
{
delete[] data;
}
// 2. Copy constructor: deep copy
IntArray(const IntArray& other) : data(new int[other.size]), size(other.size)
{
std::copy(other.data, other.data + size, data);
std::cout << " deep copy (constructor)\n";
}
// 3. Copy assignment operator: deep copy into an existing object
IntArray& operator=(const IntArray& other)
{
int* fresh = new int[other.size]; // allocate first
std::copy(other.data, other.data + other.size, fresh);
delete[] data; // then release the old block
data = fresh;
size = other.size;
std::cout << " deep copy (assignment)\n";
return *this; // return the current object
}
void set(int i, int v) { data[i] = v; }
int get(int i) const { return data[i]; }
};
int main()
{
IntArray a(3);
a.set(0, 10);
IntArray b = a; // copy constructor
b.set(0, 99);
IntArray c(5);
c = a; // copy assignment
c.set(0, 7);
std::cout << "a[0] = " << a.get(0) << ", b[0] = " << b.get(0)
<< ", c[0] = " << c.get(0) << '\n';
return 0;
}
Output:
construct (size 3)
deep copy (constructor)
construct (size 5)
deep copy (assignment)
a[0] = 10, b[0] = 99, c[0] = 7
The copy assignment operator is written IntArray& operator=(const IntArray& other). It's a function with a special name; the full syntax is explained in Operator Overloading, and the return *this; line in The this Pointer. For now, notice how it differs from the copy constructor:
| Copy constructor | Copy assignment operator |
|---|---|
| Creates a new object | Overwrites an existing object |
IntArray b = a; / IntArray b(a); | c = a; |
| Nothing to clean up first | Must release the old block (c had 5 elements) |
| No return value | Returns *this by reference so x = y = z works |
The assignment allocates and copies before deleting the old block. That order makes it safe even for self-assignment (a = a;): if we deleted first, we would then copy from the block we just freed.
Rule of Five and Rule of Zero
C++11 added two more special member functions, the move constructor and move assignment operator, which "steal" resources from temporaries instead of copying them (see Move Semantics & Rvalue References). Here is the complete family:
| Special member | Typical signature | The compiler generates it when ... |
|---|---|---|
| Default constructor | X() | no constructor of any kind is user-declared |
| Destructor | ~X() | none is user-declared |
| Copy constructor | X(const X&) | none is user-declared (defined as deleted if a move operation is user-declared) |
| Copy assignment | X& operator=(const X&) | same as the copy constructor |
| Move constructor (C++11) | X(X&&) | no copy operation, move operation or destructor is user-declared |
| Move assignment (C++11) | X& operator=(X&&) | same as the move constructor |
(Generating the copy operations for a class that has a user-declared destructor still happens for backward compatibility, but it is deprecated since C++11, precisely because of the Rule of Three.)
Rule of Five (C++11): if you write any of the destructor, copy constructor, copy assignment, move constructor or move assignment, think about all five.
Rule of Zero: better still, design classes so you need to write none of them. Let members that already manage themselves (
std::string,std::vector, smart pointers) own the resources.
#include <iostream>
#include <string>
#include <vector>
// Rule of zero: members manage themselves, so we write no destructor,
// no copy constructor and no copy assignment.
class Playlist
{
private:
std::string name;
std::vector<std::string> songs;
public:
explicit Playlist(const std::string& n) : name(n) {}
void add(const std::string& song) { songs.push_back(song); }
void show() const
{
std::cout << name << ":";
for (const std::string& s : songs)
std::cout << " [" << s << "]";
std::cout << '\n';
}
};
int main()
{
Playlist p1("Road trip");
p1.add("Song A");
p1.add("Song B");
Playlist p2 = p1; // deep copy for free: string and vector copy themselves
p2.add("Song C");
p1.show();
p2.show();
return 0;
}
Output:
Road trip: [Song A] [Song B]
Road trip: [Song A] [Song B] [Song C]
The generated copy constructor copies name and songs using their copy constructors, which already do deep copies. No pointers, no delete, no bugs. Most classes you write should look like this.
Sometimes copying makes no sense at all (an object representing a unique printer or a network socket). Then we delete the copy operations (C++11):
class Printer
{
public:
Printer() = default;
Printer(const Printer&) = delete; // no copying
Printer& operator=(const Printer&) = delete; // no copy assignment
};
Printer p1;
Printer p2 = p1; // error
error: use of deleted function ‘Printer::Printer(const Printer&)’
Common Mistakes
Giving a constructor a return type, even
void. Then it's not a constructor at all and the code doesn't compile.Expecting a default constructor after writing another constructor. Add
ClassName() = default;if you need it.Writing the initializer list in a different order from the declarations, and relying on that order. Initialization always follows declaration order.
Assigning
constor reference members in the constructor body instead of the initializer list.Writing
Student s();to call the default constructor. It declares a function. UseStudent s;orStudent s{};.Owning a raw pointer but relying on the generated copy operations: shared data and double deletes. Follow the Rule of Three, or better, the Rule of Zero.
Forgetting
expliciton single-argument constructors, which lets surprising implicit conversions compile.Throwing an exception out of a destructor. Destructors are
noexcept, so the program callsstd::terminate().
Interview / GATE Questions
1. Can a constructor be virtual? Can a destructor?
A constructor cannot be virtual: when it runs, the object's exact type is being decided, so there's nothing to dispatch on. A destructor can (and in a base class used polymorphically, should) be virtual, which we'll see in Polymorphism & Virtual Functions.
2. Why does a copy constructor take its parameter by reference?
Passing by value would require copying the argument into the parameter, which would call the copy constructor again, recursively without end. The language therefore forbids a constructor whose first parameter is the class type by value; the parameter is const ClassName& so that const objects and temporaries can also be copied.
3. In int main() { A a; B b; C c; }, in what order are the destructors called?
~C(), then ~B(), then ~A(). Local objects are destroyed in the reverse order of their construction.
4. How many times are the constructor and destructor called for Student arr[5];?
The default constructor is called 5 times (for arr[0] to arr[4], in that order) and the destructor 5 times when arr goes out of scope, in reverse order (arr[4] first). If Student had no default constructor, the declaration would not compile.
5. Which function is called in each line? Book b = a; and b = a;
The first creates a new object, so it calls the copy constructor (the = here is initialization syntax, not assignment). The second assigns to an existing object, so it calls the copy assignment operator.
6. A class declares int b; int a; (in that order) and its constructor is X(int v) : a(v), b(a + 1) {}. What is b after X x(5);?
Undefined. Members are initialized in declaration order, so b is initialized first, using a before a has been initialized. Reading an uninitialized int is undefined behavior. a ends up as 5.
7. What is the Rule of Three, and why does it exist?
If a class needs a user-defined destructor, copy constructor or copy assignment operator, it almost certainly needs all three. Needing one usually means the class owns a resource (such as heap memory through a raw pointer); the compiler-generated versions of the other two would copy only the handle, causing shared state and double release. C++11 extends it to the Rule of Five (adding the move operations), and the Rule of Zero recommends avoiding all of them by using self-managing members.
Summary
A constructor has the class's name and no return type, runs automatically at creation, and can be overloaded. A destructor (
~ClassName) runs automatically when the lifetime ends; there is only one.The compiler provides a default constructor only if we declare no constructors;
= defaultbrings it back.Use the member initializer list to initialize members; it's required for
constand reference members. Initialization follows declaration order.Delegating constructors (C++11) remove duplicated setup;
explicitblocks unwanted implicit conversions.Local objects are destroyed in reverse order of construction. RAII ties a resource's lifetime to an object's, so cleanup is automatic on every exit path.
The copy constructor (
X(const X&)) runs on initialization from another object, pass-by-value and (non-elided) return-by-value. C++17 guarantees elision when returning a temporary.Generated copies are shallow. Classes owning raw resources need a deep copy and must follow the Rule of Three/Five; prefer the Rule of Zero.