A constructor in C++ is a special member function of a class that is automatically executed when an object is created.Its main purpose is to initialize data members and set up resources (memory, files, etc.).
void)#include <iostream>using namespace std; class Student {public: int roll; // Constructor Student() { roll = 1; cout << "Constructor called" << endl; }}; int main() { Student s1; // Constructor runs here cout << s1.roll; return 0;}Constructor called1👉 As soon as s1 is created, the constructor runs automatically.
A constructor with no parameters.
class Test {public: Test() { cout << "Default Constructor"; }};Used when you simply write:
Test t;Takes arguments to initialize values.
class Student {public: int roll; Student(int r) { roll = r; }}; int main() { Student s(10);}👉 Here 10 is passed to the constructor.
Creates a new object from an existing object.
class Demo {public: int x; Demo(int a) { x = a; } Demo(Demo &d) { // Copy constructor x = d.x; }};Used like:
Demo d1(5);Demo d2 = d1; // Copy constructor calledMultiple constructors in the same class (different parameters).
class Example {public: Example() { cout << "Default\n"; } Example(int a) { cout << "Parameterized\n"; }};✔ Automatically initialize objects✔ Reduce coding errors✔ Used in Object-Oriented Programming for proper setup✔ Helps in resource management✔ Makes code cleaner and safer