Legacy C++ › 3. Classes and Object-Oriented Programming
Constructors, Destructors and Initializer Lists
Object lifetime, member initialization order and conversion constructors.
beginner #constructors#destructors#initializer-list#explicit#object-lifetime
Explanation
A constructor initializes a new object; the destructor (~Class()) cleans up when the object dies. Key rules:
- Members are initialized in declaration order, before the constructor body runs. Use the member initializer list (
: a_(x), b_(y)) rather than assigning in the body. It is required forconstmembers, references, and base classes or members without a default constructor. - If you declare no constructor, the compiler provides a default one. If you declare any constructor, it does not.
- The compiler also generates a copy constructor, copy assignment operator and destructor if you do not.
- A constructor callable with one argument acts as an implicit conversion; mark it
explicitto prevent surprising conversions. - Local objects are destroyed in reverse order of construction.
Example
#include <iostream>
#include <string>
class Person {
std::string name_;
const int id_; // const: must use the initializer list
int& counter_; // reference: same
public:
Person(const std::string& n, int id, int& counter)
: name_(n), id_(id), counter_(counter) {
++counter_;
std::cout << "construct " << name_ << "\n";
}
~Person() {
--counter_;
std::cout << "destroy " << name_ << "\n";
}
};
class Meters {
double v_;
public:
explicit Meters(double v) : v_(v) {} // no accidental double -> Meters
double value() const { return v_; }
};
void show(Meters m) { std::cout << m.value() << "m\n"; }
int main() {
int alive = 0;
{
Person a("Ann", 1, alive);
Person b("Bob", 2, alive);
std::cout << "alive: " << alive << "\n"; // 2
} // destroys Bob, then Ann
std::cout << "alive: " << alive << "\n"; // 0
show(Meters(5.0));
// show(5.0); // error because of explicit
return 0;
}
Common pitfalls
- Initializer-list order does not change the real order: members follow their declaration order, so
a_(b_)can read an uninitializedb_. - Assigning in the body instead of initializing means default-construct then assign: slower, and impossible for const/reference members.
- Base class destructors must be
virtualif you delete derived objects through a base pointer (see Virtual Functions). - Never call virtual functions from a constructor or destructor: the derived part does not exist (or no longer exists), so the base version runs.
- “Most vexing parse”:
Widget w();declares a function, not an object. WriteWidget w;.
Legacy vs modern
C++11 adds delegating constructors, in-class member initializers, = default, = delete, and brace initialization. See also RAII and the Rule of Three.
Exercises
1. In what order are Person a; Person b; destroyed?
b first, then a: reverse of construction.
2. Why does explicit matter on a single-argument constructor?
Without it, show(5.0) would silently create a Meters temporary; explicit forces you to write the conversion.