Learn C++
#include "oopbasics/constructors.hpp"

Constructors in C++

//concept

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.

//how it works
1

Automatic initialization

Dog d("Rex"); runs the matching constructor immediately — the object is valid from the first line you can name it.

2

Overload freely

Dog(), Dog(string), Dog(const Dog&) can all coexist; overload resolution picks by arguments exactly like free functions.

3

Initializer lists

: name(n) constructs members in place. Assignment inside the body would default-construct first, then overwrite — wasteful and impossible for const members.

4

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.

//example
#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;
}
Output
unnamed, Rex
1Dog a; matches the no-arg constructor, initializing name to unnamed via its initializer list.
2Dog b("Rex"); matches the string constructor, initializing name directly to Rex.
3Both objects print their own established state — no separate init call was ever needed.
//use cases
Guaranteeing valid objects by requiring setup data as constructor parameters
Offering several construction styles (empty, from values, from another object) via overloads
Using initializer lists for const members, references, and efficiency
Restoring suppressed defaults explicitly with = default

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.