Types of Constructors in C++

C++ supports several types of constructors to handle different scenarios of object creation.

 

  • Default Constructor

A default constructor takes no parameters. It is used to initialize objects with default values and is invoked automatically when no arguments are passed during object creation.

Syntax:

class Example {

public:

    Example() {

        // default initialization

    }

};

Example:

class Student {

public:

    Student() {

        cout << “Default Constructor called.”;

    }

};

Student s1; // Calls default constructor

 

  • Parameterized Constructor

Parameterized constructors accept arguments to allow initialization with specific values. They provide flexibility in setting object states at the time of creation.

 

Syntax:

class ClassName {

public:

    ClassName(int a, float b); // with parameters

};

 

Example:

class Student {

    int age;

public:

    Student(int a) {

        age = a;

        cout << “Age is: ” << age;

    }

};

Student s1(21);

 

  • Copy Constructor

A copy constructor initializes a new object as a copy of an existing object. It is invoked when an object is passed by value, returned from a function, or explicitly copied.

 

Syntax:

ClassName(const ClassName &obj);

 

Example:

class Student {

    int age;

public:

    Student(int a) { age = a; }

    Student(const Student &s) {

        age = s.age;

        cout << “Copied age: ” << age;

    }

};

Student s1(20);

Student s2 = s1;

 

  • Constructor Overloading

Constructor overloading allows multiple constructors in the same class with different parameters. This supports flexible initialization based on how objects are created.

 

Example:

class Student {

public:

    Student() {

        cout << “Default\n”;

    }

    Student(int a) {

        cout << “Parameterized\n”;

    }

};

Student s1;

Student s2(5);

 

  • Dynamic Constructor

Dynamic constructors allocate memory at runtime using new. These are useful when object sizes are unknown at compile time.

 

Example:

class Array {

    int* ptr;

public:

    Array(int size) {

        ptr = new int[size];

        cout << “Memory allocated.”;

    }

    ~Array() {

        delete[] ptr;

    }

};

Array a1(5);