Constructors
Lesson outline
Introduction to Constructors
A constructor in C++ is a special member function that is automatically called when an object is created. It has the same name as the class and has no return type (not even void).
Constructors primarily initialize data members and may acquire resources as an object begins its lifetime. Prefer initializing members in the member-initializer list rather than assigning inside the body.
Basic Constructor Example
Here is a simple example using a member-initializer list and a const member function:
Default Constructors
If you do not declare any constructors, the compiler implicitly declares a default constructor (with no parameters). If a base class or member cannot be default-initialized, that implicitly-declared constructor will be defined as deleted.
If you declare another constructor, the default constructor is no longer implicitly declared; you can still request it explicitly with = default.
Best Practices
- Initialize members in the member-initializer list; it is required for
constand reference members and is generally more efficient. - Keep constructor logic simple; avoid heavy computations or complex control flow.
- Mark single-parameter constructors
explicitto prevent unintended implicit conversions. - Prefer in-class member initializers for sensible defaults (e.g.,
int x{0};). - Remember: members are initialized in the order they are declared in the class, not the order listed in the initializer list.