C++ Constructors
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:
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
// Constructor using a member-initializer list
Person(string n, int a) : name(std::move(n)), age(a) {}
void display() const {
cout << name << " is " << age << " years old." << '\n';
}
};
int main() {
Person p1("Alice", 25);
p1.display();
return 0;
}
Alice is 25 years old.
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`.
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "A default ctor\n"; } // user-provided default constructor
};
class B {
public:
B(int) { /* ... */ } // declaring any ctor prevents an implicit default ctor
B() = default; // explicitly request the default constructor
};
int main() {
A a; // prints: A default ctor
B b1(42); // OK
B b2; // OK due to 'B() = default;'
}
Best Practices
- Initialize members in the member-initializer list; it is required for `const` and reference members and is generally more efficient.
- Keep constructor logic simple; avoid heavy computations or complex control flow.
- Mark single-parameter constructors `explicit` to 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.