Constructors in C++
A constructor runs automatically at object creation, establishing the initial valid state — no more two-step create-then-init. Same name as the class, no return type, and overloadable: a default (no-arg), a parameterized, and a copy constructor can coexist, with the compiler generating defaults when you write none.
Member initializer lists (Dog(string n) : name(n) {}) initialize members directly instead of default-constructing then assigning — mandatory for const/reference members and measurably faster for class-type members. Delegating constructors (C++11) let one constructor call another, killing duplicated setup logic.
Automatic initialization
Dog d("Rex"); runs the matching constructor immediately — the object is valid from the first line you can name it.
Overload freely
Dog(), Dog(string), Dog(const Dog&) can all coexist; overload resolution picks by arguments exactly like free functions.
Initializer lists
: name(n) constructs members in place. Assignment inside the body would default-construct first, then overwrite — wasteful and impossible for const members.
Compiler-generated defaults
With no user constructors you get a default, copy, and move constructor free — writing any custom one suppresses some, so = default restores them explicitly.
#include <iostream>#include <string> class Dog {public: std::string name; Dog() : name("unnamed") {} Dog(const std::string& n) : name(n) {}}; int main() { Dog a; Dog b("Rex"); std::cout << a.name << ", " << b.name << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.