Default Constructor
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 18 of 104.
A default constructor is a constructor that can be called with no arguments. It initializes an object when no initial values are provided. Every class needs a way to create objects in a valid default state.
If you don't define any constructor, the compiler generates an implicit default constructor that does nothing for primitive types and calls default constructors for member objects.
class Player {
int health;
int score;
public:
Player() { // Default constructor
health = 100;
score = 0;
}
};
Player p1; // Calls default constructor
Player p2{}; // Also calls default constructorOnce you define any constructor (like a parameterized one), the compiler no longer generates a default constructor. You must explicitly define one if you still need it.
class Enemy {
int damage;
public:
Enemy(int d) : damage(d) {} // Parameterized constructor only
};
Enemy e1(10); // Works
Enemy e2; // Error! No default constructorIn modern C++, you can explicitly request the compiler-generated default constructor using = default:
class Item {
int id;
public:
Item() = default; // Compiler generates default constructor
Item(int i) : id(i) {}
};Default constructors are essential for creating arrays of objects and for classes used in containers like std::vector, which may need to construct elements without arguments.
Challenge
EasyLet's build a simple counter system that demonstrates how default constructors initialize objects to a valid starting state.
You'll create two files to organize your code:
Counter.h: Define aCounterclass that tracks a count value. Your class should have:- A private
countattribute (integer) - A private
nameattribute (string) to identify the counter - A default constructor that initializes
countto0andnameto"Unnamed", then prints"Counter created: <name>" - An
increment()method that increases the count by 1 - A
getCount()method that returns the current count - A
getName()method that returns the counter's name
- A private
main.cpp: Demonstrate that default constructors work when creating objects in different ways. Read a number from input indicating how many times to increment the counter, then:- Create a Counter using direct initialization:
Counter c1; - Create another Counter using brace initialization:
Counter c2{}; - Increment
c1the number of times specified by the input - Print
"<name>: <count>"for c1 - Print
"<name>: <count>"for c2
- Create a Counter using direct initialization:
Both counters should start at 0 thanks to your default constructor, but only c1 will be incremented. This shows how default constructors ensure every object begins in a predictable, valid state regardless of how it's created.
Include your header file in main.cpp using #include "Counter.h".
Cheat sheet
A default constructor is a constructor that can be called with no arguments. It initializes an object when no initial values are provided.
class Player {
int health;
int score;
public:
Player() { // Default constructor
health = 100;
score = 0;
}
};
Player p1; // Calls default constructor
Player p2{}; // Also calls default constructorIf you don't define any constructor, the compiler generates an implicit default constructor. However, once you define any constructor (like a parameterized one), the compiler no longer generates a default constructor automatically.
class Enemy {
int damage;
public:
Enemy(int d) : damage(d) {} // Parameterized constructor only
};
Enemy e1(10); // Works
Enemy e2; // Error! No default constructorYou can explicitly request the compiler-generated default constructor using = default:
class Item {
int id;
public:
Item() = default; // Compiler generates default constructor
Item(int i) : id(i) {}
};Default constructors are essential for creating arrays of objects and for classes used in containers like std::vector.
Try it yourself
#include <iostream>
#include "Counter.h"
using namespace std;
int main() {
// Read the number of times to increment
int n;
cin >> n;
// TODO: Create a Counter using direct initialization: Counter c1;
// TODO: Create another Counter using brace initialization: Counter c2{};
// TODO: Increment c1 the number of times specified by n
// TODO: Print "<name>: <count>" for c1
// TODO: Print "<name>: <count>" for c2
return 0;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container