Constructors in C++

 Constructors

A special member function of a class that is automatically called when an object is created.

  • Same name as the class
  • No return type (not even void)
  • Called automatically when an object is created
  • Used to initialize data members

Need of Constructors

Constructors ensure:

  • Proper initialization of objects
  • Cleaner code (no need to call a separate function for initialization)
  • Avoiding uninitialized variables
  • User-defined default values
  • Automatically Initialize Objects
  • Ensure Object Integrity
  • Perform Resource Allocation
  • Support Encapsulation

 

RULES OF CONSTRUCTORS

Rule

Meaning

Same name as class

Mandatory

No return type

Even void is not allowed

Automatically called

When object created

Cannot be virtual

Constructors cannot be virtual

Can be overloaded

Yes

Can be private

Yes (Singleton pattern)

 

Types of Constructors in C++

C++ provides 5 main types of constructors:

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Dynamic (or Constructor with Dynamic Allocation)

1.    DEFAULT CONSTRUCTOR

A constructor that takes no parameters.

  • Automatically initializes objects
  • Required simple initialization
  • Useful in large programs where many objects are created

 

Syntax

    class_ name () {      // Default Constructor

        Variable = 0;

        cout << "Default constructor called\n";

    }

 

Usage

  • In a fixed initial value
  • Use in arrays of objects

 

Example

#include <iostream>

using namespace std;

 

class Student {

    int roll;

public:

    Student() {      // Default Constructor

        roll = 0;

        cout << "Default constructor called\n";

    }

 

    void show() {

        cout << "Roll = " << roll << endl;

    }

};

 

int main() {

    Student s;   // Default constructor invoked

    s.show();

}


2.    PARAMETERIZED CONSTRUCTOR

A constructor that accepts arguments.

initialize objects with different values

Eliminates the need of separate setter methods

 

Syntax

    class_ name (int a, int b) {   // Parameterized Constructor

        x = a;

        y = b;

    }

 

Usage

  • Banking systems (opening balance)
  • Geometry problems (rectangle length & width)
  • Student/Employee entries

 

Example

#include <iostream>

using namespace std;

 

class Point {

    int x, y;

public:

    Point(int a, int b) {   // Parameterized Constructor

        x = a;

        y = b;

    }

 

    void show() {

        cout << "Point: (" << x << ", " << y << ")\n";

    }

};

 

int main() {

    Point p(10, 20);   // Values passed

    p.show();

}


3.     COPY CONSTRUCTOR

A constructor that creates a new object from an existing object.

 

Syntax

ClassName(const ClassName &obj);

 

Need

  • To copy objects safely
  • Especially needed when a class uses pointers or dynamic memory

 

Usage

  • Copying strings
  • Cloning objects
  • Passing objects by value

 

Types

  • Default (compiler-generated)
  • User-defined

 

Example

#include <iostream>

using namespace std;

 

class Box {

    int length;

public:

    Box(int l) {   // Parameterized

        length = l;

    }

 

    Box(const Box &b) {   // Copy Constructor

        length = b.length;

        cout << "Copy constructor called\n";

    }

 

    void show() {

        cout << "Length = " << length << endl;

    }

};

 

int main() {

    Box b1(10);

    Box b2 = b1;   // Copy constructor invoked

 

    b2.show();

}


 

4.    DYNAMIC CONSTRUCTOR

A constructor that allocates memory dynamically

 

Need

  • To handle data whose size is unknown at compile time
  • Use for dynamic arrays, strings, file handling, and linked list nodes

 

Syntax:-

Class_ name(int s) {       // Dynamic Constructor

        size = s;

        ptr = new int[size];

 

        for(int i=0; i<size; i++)

            ptr[i] = i + 1;

 

        cout << "Dynamic constructor called\n";

    }

 

Usage

  • String classes
  • Vector-like behavior
  • Matrix creation

 

Example

#include <iostream>

using namespace std;

 

class Array {

    int *ptr;

    int size;

public:

    Array(int s) {       // Dynamic Constructor

        size = s;

        ptr = new int[size];

 

        for(int i=0; i<size; i++)

            ptr[i] = i + 1;

 

        cout << "Dynamic constructor called\n";

    }

 

    void show() {

        for(int i=0; i<size; i++)

            cout << ptr[i] << " ";

        cout << endl;

    }

 

    ~Array() {     // Destructor to free memory

        delete[] ptr;

    }

};

 

int main() {

    Array a(5);

    a.show();

}


 

Constructors cannot be:

  • Virtual
  • Inherited
  • Const
  • Static

Constructors CAN be:

  • Overloaded
  • Defined outside class (using scope resolution)

 

==================================================================

Post a Comment

0 Comments