Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Monday, September 14, 2026

Constructors and Their Types in C++

 

Constructors and Their Types in C++

A constructor is a special member function of a class that is automatically invoked when an object of that class is created. Its primary purpose is to initialize the object.

Constructors are fundamental to object-oriented programming because they ensure that an object starts its lifetime in a valid and meaningful state.

Image

Image

Image

1. What is a Constructor?

A constructor is a special member function having the same name as the class.

For example:

class Student
{
public:
    Student()
    {
        cout << "Constructor called";
    }
};

When an object is created:

Student s;

the constructor is automatically called.

        Object Creation
              |
              ↓
        Student s;
              |
              ↓
     Student() constructor
              |
              ↓
       Object initialized

Unlike an ordinary member function, a constructor:

  • Has the same name as the class.

  • Has no return type, not even void.

  • Is called automatically when an object is created.

  • Is normally used to initialize data members.

  • Can be overloaded.

  • Can have parameters.

  • Can have default arguments.

  • Cannot be declared static.

  • Is not inherited in the usual sense.


2. Basic Syntax of a Constructor

class ClassName
{
public:
    ClassName()
    {
        // initialization
    }
};

Example:

class Student
{
    int rollNo;

public:
    Student()
    {
        rollNo = 101;
    }
};

When:

Student s;

is executed, rollNo is initialized to 101.


3. Simple Example of Constructor

#include <iostream>
using namespace std;

class Student
{
    int rollNo;

public:

    Student()
    {
        rollNo = 101;
        cout << "Constructor called" << endl;
    }

    void display()
    {
        cout << "Roll No: " << rollNo << endl;
    }
};

int main()
{
    Student s;

    s.display();

    return 0;
}

Output

Constructor called
Roll No: 101

The statement:

Student s;

creates the object and automatically invokes:

Student()

4. Types of Constructors

The most important constructor types are:

                    Constructors
                         |
          +--------------+--------------+
          |              |              |
       Default      Parameterized      Copy
      Constructor    Constructor     Constructor

In practical C++, constructors can also involve default arguments, delegating constructors, move constructors, and other modern features. For the present OOP unit, default, parameterized, and copy constructors are the core types.



Image




5. Default Constructor

A constructor that can be called without providing arguments is called a default constructor.

Example:

class Student
{
public:

    Student()
    {
        cout << "Default constructor";
    }
};

Object creation:

Student s;

automatically calls the constructor.

Example

#include <iostream>
using namespace std;

class Student
{
    int rollNo;

public:

    Student()
    {
        rollNo = 100;
    }

    void display()
    {
        cout << "Roll No = " << rollNo << endl;
    }
};

int main()
{
    Student s;

    s.display();

    return 0;
}

Output

Roll No = 100

6. Important Point About Default Constructors

There is an important distinction between:

A user-provided default constructor

Student()
{
    rollNo = 100;
}

and a compiler-provided/defaulted constructor.

If the programmer does not declare any constructor, the compiler can implicitly declare a default constructor for the class in appropriate circumstances.

For example:

class Student
{
    int rollNo;
};

The class can be declared as:

Student s;

However, the integer member rollNo is not automatically initialized to zero merely because the constructor exists implicitly. For an automatic/local object, an uninitialized built-in data member can contain an indeterminate value.

Therefore, explicitly initializing data members is important.


7. Parameterized Constructor

A constructor that accepts one or more parameters is called a parameterized constructor.

Syntax

ClassName(data_type parameter1, data_type parameter2)
{
    // initialization
}

Example:

class Student
{
    int rollNo;
    float marks;

public:

    Student(int r, float m)
    {
        rollNo = r;
        marks = m;
    }
};

Object creation:

Student s(101, 85.5);

The values are passed to the constructor.


8. Example of Parameterized Constructor

#include <iostream>
using namespace std;

class Student
{
    int rollNo;
    float marks;

public:

    Student(int r, float m)
    {
        rollNo = r;
        marks = m;
    }

    void display()
    {
        cout << "Roll No: " << rollNo << endl;
        cout << "Marks: " << marks << endl;
    }
};

int main()
{
    Student s(101, 87.5);

    s.display();

    return 0;
}

Output

Roll No: 101
Marks: 87.5

Flow

Student s(101, 87.5)
          |
          ↓
 Student(int r, float m)
          |
     +----+----+
     |         |
    101       87.5
     |         |
     ↓         ↓
 rollNo      marks

9. Why Parameterized Constructors Are Useful

Suppose we want to create three student objects:

Student s1(101, 85);
Student s2(102, 91);
Student s3(103, 78);

Each object can be initialized with different values.

s1 → rollNo = 101, marks = 85
s2 → rollNo = 102, marks = 91
s3 → rollNo = 103, marks = 78

Thus, parameterized constructors provide a convenient way to initialize different objects with different values at the time of creation.


10. Constructor Using Initialization List

A parameterized constructor is often better written using a constructor initialization list.

class Student
{
    int rollNo;
    float marks;

public:

    Student(int r, float m) : rollNo(r), marks(m)
    {
    }
};

This directly initializes the data members.

For example:

Student s(101, 85.5);

The initialization list is particularly important for:

  • const data members

  • Reference data members

  • Members without default constructors

  • Efficient initialization of class-type members

Recommended Style

Student(int r, float m)
    : rollNo(r), marks(m)
{
}

rather than:

Student(int r, float m)
{
    rollNo = r;
    marks = m;
}

Both can work, but they are not technically identical: the initialization list performs initialization, while assignments in the constructor body perform assignment after the members have already been initialized.


11. Copy Constructor

A copy constructor is a constructor used to initialize a new object from an existing object of the same class.

General Syntax

ClassName(const ClassName &object)
{
    // copy data
}

Example:

class Student
{
    int rollNo;

public:

    Student(int r)
    {
        rollNo = r;
    }

    Student(const Student &s)
    {
        rollNo = s.rollNo;
    }
};

Here:

Student s1(101);
Student s2(s1);

creates s2 as a copy of s1.


12. Example of Copy Constructor

#include <iostream>
using namespace std;

class Student
{
    int rollNo;
    float marks;

public:

    Student(int r, float m)
    {
        rollNo = r;
        marks = m;
    }

    Student(const Student &s)
    {
        rollNo = s.rollNo;
        marks = s.marks;
    }

    void display()
    {
        cout << "Roll No: " << rollNo << endl;
        cout << "Marks: " << marks << endl;
    }
};

int main()
{
    Student s1(101, 88.5);

    Student s2(s1);

    cout << "First object:" << endl;
    s1.display();

    cout << "\nCopied object:" << endl;
    s2.display();

    return 0;
}

Output

First object:
Roll No: 101
Marks: 88.5

Copied object:
Roll No: 101
Marks: 88.5

Visual Representation

       Existing Object
          s1
    +-------------+
    | rollNo 101  |
    | marks  88.5 |
    +-------------+
           |
           | copy constructor
           ↓
       New Object
          s2
    +-------------+
    | rollNo 101  |
    | marks  88.5 |
    +-------------+

13. Why const Reference Is Used in a Copy Constructor

The standard form is:

Student(const Student &s)

There are two important parts.

&

The object is passed by reference, avoiding creation of another copy.

const

The source object should not be modified during copying.

Therefore:

const Student &s

is the conventional and appropriate form for a copy constructor.


14. When Is a Copy Constructor Called?

A copy constructor can be invoked in several situations.

1. Initialization from another object

Student s1(101);
Student s2(s1);

2. Copy initialization

Student s1(101);
Student s2 = s1;

3. Passing an object by value

void display(Student s)
{
}

Calling:

display(s1);

may require a copy of s1.

4. Returning an object by value

Student createStudent()
{
    Student s(101);
    return s;
}

Copy/move construction may be involved depending on the situation and compiler optimizations such as copy elision.


15. Compiler-Generated Copy Constructor

If we do not define a copy constructor, C++ can provide an implicitly declared copy constructor.

Example:

class Student
{
public:
    int rollNo;
};

Then:

Student s1;
s1.rollNo = 101;

Student s2 = s1;

The compiler-generated copy constructor performs member-wise copying.

Conceptually:

s1.rollNo
    |
    | copy
    ↓
s2.rollNo

For classes containing only ordinary value-type members, this is usually sufficient.


16. Shallow Copy

Consider a class containing a pointer:

class Student
{
public:
    int *marks;

    Student()
    {
        marks = new int(90);
    }
};

If the default copy constructor is used:

Student s1;
Student s2 = s1;

the pointer value is copied.

Conceptually:

s1.marks ─────┐
              ↓
          +-------+
          |  90   |
          +-------+
              ↑
              |
s2.marks ─────┘

Both objects point to the same dynamically allocated memory.

This is commonly called a shallow copy.

It can lead to serious problems when a class owns dynamically allocated resources.


17. Deep Copy

A deep copy creates separate dynamically allocated memory for the copied object and copies the actual data.

Example:

#include <iostream>
using namespace std;

class Student
{
    int *marks;

public:

    Student(int m)
    {
        marks = new int(m);
    }

    Student(const Student &s)
    {
        marks = new int(*s.marks);
    }

    void display()
    {
        cout << "Marks = " << *marks << endl;
    }

    ~Student()
    {
        delete marks;
    }
};

int main()
{
    Student s1(90);

    Student s2(s1);

    s2.display();

    return 0;
}

Here:

marks = new int(*s.marks);

creates a new memory location and copies the value.

             s1
             |
             ↓
          +-----+
          | 90  |
          +-----+

             s2
             |
             ↓
          +-----+
          | 90  |
          +-----+

The two objects own separate memory.

Image

Image

Image

Image

Image


18. Constructor Overloading

Since constructors can be overloaded, a class can have multiple constructors with different parameter lists.

Example:

class Student
{
public:

    Student()
    {
        cout << "Default constructor" << endl;
    }

    Student(int r)
    {
        cout << "Parameterized constructor" << endl;
    }

    Student(int r, float m)
    {
        cout << "Parameterized constructor with two arguments" << endl;
    }
};

Now:

Student s1;
Student s2(101);
Student s3(101, 85.5);

call different constructors.

This is an application of function overloading, because constructors are overloaded based on their parameter lists.


19. Constructor vs Normal Member Function

ConstructorNormal Member Function
Same name as classCan have any valid name
No return typeHas a return type or void
Automatically called during object initializationUsually called explicitly
Initializes objectPerforms an operation
Called when object is createdCan be called multiple times
Cannot be staticCan be static
Can be overloadedCan be overloaded

20. Constructor vs Destructor

A destructor is used for cleanup when an object reaches the end of its lifetime.

ConstructorDestructor
Initializes objectPerforms cleanup
Same name as class~ClassName()
Called when object is createdCalled when object is destroyed
Can be overloadedCannot be overloaded
Can accept parametersTakes no parameters
Multiple constructors possibleOnly one destructor per class

Example:

class Student
{
public:

    Student()
    {
        cout << "Constructor" << endl;
    }

    ~Student()
    {
        cout << "Destructor" << endl;
    }
};

21. Constructor with Default Arguments

A constructor can also use default arguments.

class Student
{
    int rollNo;
    int marks;

public:

    Student(int r = 0, int m = 0)
    {
        rollNo = r;
        marks = m;
    }
};

Now:

Student s1;
Student s2(101);
Student s3(101, 85);

are all possible.

The compiler supplies default values for missing arguments.

However, when designing a class, default arguments should be used carefully because they can interact with overloaded constructors and create ambiguity.


22. Constructor Initialization of const and Reference Members

A constructor initialization list becomes necessary for certain members.

Example:

class Test
{
    const int x;
    int &ref;

public:

    Test(int a, int b)
        : x(a), ref(b)
    {
    }
};

Here x and ref must be initialized through the initialization list.

This is an important reason why constructor initialization lists should be understood properly.


23. Constructors and Dynamic Objects

Constructors are automatically called even when objects are dynamically allocated.

class Student
{
public:

    Student()
    {
        cout << "Constructor called" << endl;
    }

    ~Student()
    {
        cout << "Destructor called" << endl;
    }
};

Now:

Student *ptr = new Student;

calls the constructor.

When:

delete ptr;

is executed, the destructor is called.

new Student
     ↓
Constructor
     ↓
Object created
     ↓
delete ptr
     ↓
Destructor

24. Important Examination Points

Constructor

A constructor is a special member function that is automatically called when an object is created and is primarily used to initialize the object.

Default Constructor

A constructor that can be invoked without arguments is called a default constructor.

Parameterized Constructor

A constructor that accepts one or more parameters to initialize an object with specified values is called a parameterized constructor.

Copy Constructor

A copy constructor initializes a new object using an existing object of the same class.

Standard form:

ClassName(const ClassName &obj);

Deep Copy

Deep copying creates an independent copy of dynamically allocated resources instead of merely copying their addresses.


25. Quick Revision

                    CONSTRUCTOR
                         |
          +--------------+--------------+
          |              |              |
       DEFAULT      PARAMETERIZED      COPY
          |              |              |
     Student()      Student(int)   Student(const Student&)
          |              |              |
     No argument     Initial values    Existing object

Example

class Student
{
    int rollNo;

public:

    // Default constructor
    Student()
    {
        rollNo = 0;
    }

    // Parameterized constructor
    Student(int r)
    {
        rollNo = r;
    }

    // Copy constructor
    Student(const Student &s)
    {
        rollNo = s.rollNo;
    }
};

Object creation:

Student s1;          // Default constructor

Student s2(101);     // Parameterized constructor

Student s3(s2);      // Copy constructor

One important memory rule

Constructor → Object initialization

Destructor  → Object cleanup

Copy Constructor → Initialization of a new object
                   from an existing object

And remember:

Constructor = same class name + no return type + automatic invocation during object initialization.

No comments:

Post a Comment