What a constructor does
A constructor is a special member function that runs automatically when an object of its class is created. Its job is to give the object a valid starting state, usually by setting its member variables. A constructor has the same name as its class and no return type, not even void.
Many readers first wonder: why is a constructor needed in a class? The short answer is that a constructor makes sure the object is set up before any code uses it.
Here is a small class with one constructor:
#include <iostream>
#include <string>
class Book {
public:
Book(std::string title, int pages) : title_(title), pages_(pages) {}
void print() const {
std::cout << title_ << " (" << pages_ << " pages)\n";
}
private:
std::string title_;
int pages_;
};
int main() {
Book book("Dune", 412); // the constructor runs here
book.print();
return 0;
}
The output is:
Dune (412 pages)
When book is created, the constructor receives "Dune" and 412 and stores them in the member variables. You do not call a constructor the way you call a normal function. You create the object, and the arguments go in the parentheses right after its name.
In C++, a struct can have constructors too, and the same rules apply. The main difference between a struct and a class is the default access level.
The member initializer list
The part after the colon, : title_(title), pages_(pages), is the member initializer list. Each member is set up with its value before the constructor body runs.
Assigning inside the body would also work for this class (title_ = title;). But then each member is first set up with a default value and only afterward given the real one. The initializer list skips that extra step. It is also required for const members and reference members, because those cannot be assigned after they are set up.
Default constructors
A default constructor can be called with no arguments, so you can write Counter counter;. You can write your own:
class Counter {
public:
Counter() : count_(0) {} // your own default constructor
private:
int count_;
};
You can also ask the compiler for one with = default. Since C++11, a default member initializer lets you give a value right where the member is declared:
class Flag {
public:
Flag() = default; // the compiler writes the default constructor
private:
bool is_set_ = false; // default member initializer
};
If you write no constructor at all, the compiler generates a default one. That generated constructor does not give a value to a built-in member such as int, unless the member has a default member initializer. Reading an int member that was never set is undefined behavior. Members of class types, such as std::string, are set up by their own constructors, so a std::string member starts out empty.
Once you declare any constructor, the compiler stops generating a default constructor for you. If you still want one, write it yourself or use = default.
Several constructors
A class can have more than one constructor, as long as their parameter lists differ. This is called constructor overloading.
class Rectangle {
public:
Rectangle() : width_(1), height_(1) {} // 1 x 1
Rectangle(int side) : width_(side), height_(side) {} // square
Rectangle(int width, int height) : width_(width), height_(height) {}
private:
int width_;
int height_;
};
// Rectangle a; // uses the first constructor
// Rectangle b(5); // uses the second: 5 x 5
// Rectangle c(4, 2); // uses the third: 4 x 2
Standard library types use the same idea. std::vector has several constructors, which is one reason c vector initialization has more than one form.
Explicit constructors
A constructor that takes one argument can let the compiler convert a value into an object without being asked. The explicit keyword turns that off:
class Meters {
public:
explicit Meters(double value) : value_(value) {}
private:
double value_;
};
void report(Meters m) { /* ... */ }
int main() {
// report(5.0); // error: explicit blocks the implicit conversion
report(Meters(5.0)); // OK: the conversion is written out
}
As a general habit, mark single-argument constructors explicit unless you want implicit conversions.
Initialization order
Members are initialized in the order they are declared in the class, not in the order they appear in the initializer list. This class reads b_ before it has a value:
class Pair {
public:
Pair(int x) : b_(x), a_(b_ + 1) {} // a_ is set first, and it uses b_ too early
private:
int a_; // declared first, so it is initialized first
int b_;
};
Here a_ is initialized first because it is declared first, so b_ + 1 uses b_ before it has a value. That is undefined behavior. Many compilers warn about a mismatched initializer order when warnings are turned on. To avoid the problem, list the initializers in the same order you declare the members, and keep each initializer simple.
Base classes and member objects
When an object of a derived class is created, the base class constructor runs first. Then the derived class’s members are initialized in declaration order, and the derived constructor’s body runs last. This ordering matters for inheritance in c, because the derived constructor is responsible for calling the base constructor:
class Base {
public:
Base(int id) : id_(id) {}
private:
int id_;
};
class Derived : public Base {
public:
Derived(int id, int level) : Base(id), level_(level) {}
private:
int level_;
};
Copy constructors
A copy constructor creates a new object as a copy of an existing one. Its usual form is Book(const Book& other);. If you do not write one, the compiler generates a copy constructor that copies each member. That is often the right behavior for simple classes. Classes that manage raw memory or other resources usually need to think about copying more carefully.
Brace initialization
Since C++11, you can also write Book book{"Dune", 412};. Braces reject narrowing conversions, so passing a double variable to an int parameter is a compile error instead of a silent truncation.
Things to watch for
- You cannot call a constructor on an existing object, as in
book.Book("Other", 1);. Constructors run only when an object is created. - Constructors cannot be
virtual. - Avoid calling virtual functions from a constructor. While the base part is being constructed, a virtual call uses the version defined in that base class, not one in a derived class.
- If a constructor throws an exception, the object is never considered fully created, so its destructor does not run. Members that were already set up are cleaned up.
- A private constructor stops outside code from creating objects directly. This is one of the access modifiers in c rules that apply to constructors, and it is a common way to control how objects are made.
Key points
- A constructor has the class name, no return type, and runs when an object is created.
- Use the member initializer list to set members. It is required for
constand reference members. - The compiler generates a default constructor only if you declare no constructors of your own.
- Mark single-argument constructors
explicitunless you want implicit conversions. - Members are initialized in the order they are declared, so keep initializers in that same order.