C++ Constructors

πŸ—οΈ C++ Constructors

A constructor in C++ is a special class method that is automatically called when an object is created.
Its main purpose is to initialize the data members of a class.


πŸ”Ή 1. Key Properties of Constructors

  • Name is same as class name

  • No return type (not even void)

  • Called automatically at object creation

  • Used to initialize objects


πŸ”Ή 2. Default Constructor

A constructor with no parameters.

class Demo {
public:
Demo() {
cout << "Default Constructor Called";
}
};
int main() {
Demo d;
}


πŸ”Ή 3. Parameterized Constructor

A constructor that accepts parameters.

class Student {
public:
int id;
string name;
Student(int i, string n) {
id = i;
name = n;
}
};

int main() {
Student s1(101, “Sanjit”);
}


πŸ”Ή 4. Constructor Overloading

Multiple constructors in the same class with different parameters.

class Box {
public:
int length;
Box() {
length = 0;
}

Box(int l) {
length = l;
}
};


πŸ”Ή 5. Default Values Using Constructors

class Account {
public:
int balance;
Account(int b = 0) {
balance = b;
}
};


πŸ”Ή 6. Copy Constructor

Used to create an object from another object.

class Demo {
public:
int x;
Demo(int val) {
x = val;
}

Demo(const Demo &d) {
x = d.x;
}
};

Called when:

Demo d1(10);
Demo d2 = d1; // copy constructor

πŸ”Ή 7. Constructor with this Pointer

class Test {
public:
int x;
Test(int x) {
this->x = x;
}
};


πŸ”Ή 8. Constructor Initialization List (Best Practice)

class Point {
public:
int x, y;
Point(int a, int b) : x(a), y(b) {}
};

βœ” Faster
βœ” Required for const members


πŸ”Ή 9. Explicit Constructor

Prevents implicit conversions.

class Demo {
public:
explicit Demo(int x) {
cout << x;
}
};

πŸ”Ή 10. When Constructor Is Not Written

The compiler provides a default constructor automatically if no constructor is defined.


❌ Common Mistakes

void Demo(); // ❌ not a constructor
Demo() { return; } // ❌ cannot return value

πŸ” Constructor vs Destructor

ConstructorDestructor
Initializes objectCleans resources
Called at creationCalled at destruction
Can be overloadedCannot be overloaded

πŸ“Œ Summary

  • Constructors initialize objects

  • Called automatically

  • Can be default, parameterized, copy

  • Support overloading

  • Initialization lists are recommended

You may also like...