Constructors & Initializer Lists
What is a constructor?
A special member function with the same name as the class and no return type. It runs automatically when an object is created.
Kinds of constructors
class Account {
public:
Account(); // default constructor
Account(std::string owner, double balance); // parameterized
Account(const Account& other); // copy constructor (Unit 10)
};
Member initializer list ✅
Account(std::string owner, double balance)
: owner_(std::move(owner)), balance_(balance) { }
- Initializes members directly (assignment in the body would construct then overwrite)
- Required for
constmembers, reference members and members without default constructors - Members are initialized in the order they are declared in the class, not the order in the list (compilers warn with
-Wall)
Default constructor
- If you write no constructors, the compiler generates a default one
- If you write any constructor, it doesn't — add
Account() = default;if you still want it
Delegating constructors (C++11)
Account() : Account("Guest", 0) {} // reuse another constructor
explicit
Single-argument constructors allow implicit conversions:
class Meters { public: Meters(double m); };
void run(Meters m);
run(5.0); // silently converts! Mark the constructor explicit to forbid this ✅
Default arguments in constructors
Account(std::string owner, double balance = 0);
Creating objects
Account a; // default
Account b("Asha", 500); // parameterized
Account c{"Ravi", 1000}; // brace initialization ✅
auto d = Account("Sita", 200);
Account e(); // ⚠️ declares a FUNCTION ("most vexing parse"), not an object!
Validating in the constructor
Throw an exception if arguments are invalid, so an invalid object never exists.
Example
#include <iostream>
#include <stdexcept>
#include <string>
class Account {
public:
Account() : Account("Guest", 0) {} // delegating constructor
Account(std::string owner, double balance)
: owner_(std::move(owner)), balance_(balance), id_(next_id_++) { // initializer list
if (balance_ < 0) throw std::invalid_argument("opening balance can't be negative");
std::cout << "Created #" << id_ << " for " << owner_ << '\n';
}
explicit Account(double balance) : Account("Anonymous", balance) {}
void print() const { std::cout << "#" << id_ << " " << owner_ << ": Rs. " << balance_ << '\n'; }
private:
std::string owner_;
double balance_;
const int id_; // const member: must be set in the initializer list
static inline int next_id_ = 1001;
};
class Temperature {
public:
explicit Temperature(double c) : celsius_(c) {}
double fahrenheit() const { return celsius_ * 9 / 5 + 32; }
private:
double celsius_;
};
void show(const Temperature& t) { std::cout << "Temperature: " << t.fahrenheit() << " F\n"; }
int main() {
Account guest;
Account asha("Asha", 5000);
Account ravi{ "Ravi", 1200 };
Account anon(300.0);
guest.print();
asha.print();
ravi.print();
anon.print();
try {
Account bad("Bad", -10);
} catch (const std::invalid_argument& e) {
std::cout << "Error: " << e.what() << '\n';
}
show(Temperature(37)); // OK: explicit construction
// show(37); // error: constructor is explicit, no silent conversion
return 0;
}
/* Output:
Created #1001 for Guest
Created #1002 for Asha
Created #1003 for Ravi
Created #1004 for Anonymous
#1001 Guest: Rs. 0
#1002 Asha: Rs. 5000
#1003 Ravi: Rs. 1200
#1004 Anonymous: Rs. 300
Error: opening balance can't be negative
Temperature: 98.6 F
*/