Constructors
Overview
When an Object is born (instantiated) in memory, its internal variables contain random garbage data until you manually assign them. If you create a Player object but forget to set its health, the game will crash the moment they take damage.
A Constructor is a special initialization Method that is automatically, forcefully triggered by the CPU the exact microsecond an Object is created. It guarantees that the object is born in a safe, mathematically valid state. Constructors strictly have the exact same name as the Class, and they have absolutely no return type (not even void).
Syntax
#include <iostream>
#include <string>
class Player {
public:
std::string name;
int health;
// 1. DEFAULT CONSTRUCTOR (Takes no arguments)
Player() {
name = "Unknown";
health = 100;
std::cout << "Player created!\n";
}
// 2. PARAMETERIZED CONSTRUCTOR (Overloaded)
Player(std::string pName, int pHealth) {
name = pName;
health = pHealth;
}
};
int main() {
// Triggers Default Constructor
Player p1;
// Triggers Parameterized Constructor
Player p2("Arthur", 250);
return 0;
}Common Pitfalls
- The Missing Default Constructor. If you do NOT write any constructors, C++ secretly generates an invisible, empty Default Constructor for you. HOWEVER, the moment you write a Parameterized Constructor, C++ deletes the secret default one. If you then try to write
Player p1;, the compiler will crash, demanding parameters.
Interview Questions
An Initializer List (e.g., Player() : hp(100), mp(50) {}) directly constructs the variables with the data before the constructor body executes. Standard assignment (hp = 100; inside the body) first constructs the variable with garbage data, then wastes CPU cycles overwriting it.
Real-World Example
Using high-performance Initializer Lists, which is the industry-standard way to write Constructors in modern C++.
#include <iostream>
#include <string>
class Server {
private:
std::string ip;
int port;
public:
// This syntax is drastically faster because it bypasses default initialization!
Server(std::string address, int p) : ip(address), port(p) {
std::cout << "Server bound to " << ip << ":" << port << "\n";
}
};
int main() {
Server myServer("192.168.1.1", 443);
return 0;
}Check Your Knowledge
Test your understanding of Constructors with these quick questions.