Topic 50 of 83
Constructors
Overview
Constructors are special methods called automatically when an object is created. They initialize the object's state. A Copy Constructor creates a new object as a copy of an existing one.
Syntax
cpp
class Car {
string brand;
public:
// 1. Default Constructor
Car() { brand = "Unknown"; }
// 2. Parameterized Constructor
Car(string b) { brand = b; }
// 3. Copy Constructor
Car(const Car& source) {
brand = source.brand;
}
};
Car c1; // Calls Default
Car c2("Toyota"); // Calls Parameterized
Car c3 = c2; // Calls CopyCommon Pitfalls
- Infinite recursion in the copy constructor. You MUST pass the source object by reference `const ClassName&`, NOT by value (passing by value calls the copy constructor to make the copy, creating an infinite loop).
Interview Tips
- If you define ANY constructor (like parameterized), C++ removes the implicit default constructor. You must write it manually if you still want it.
- Understand 'Shallow Copy' vs 'Deep Copy'. The default copy constructor does a shallow copy. If your class uses pointers/dynamic memory, you MUST write a custom copy constructor to do a deep copy.
Real-World Example
Using Member Initialization Lists for efficiency.
example
cpp
#include <iostream>
using namespace std;
class Player {
int health;
int mana;
public:
// Initialization list (faster than assignment inside body)
Player(int h, int m) : health(h), mana(m) {
cout << "Player spawned!" << endl;
}
};
int main() {
Player p(100, 50);
return 0;
}