Notes

Constructor in CPP [ English ]

< PrevNext >

Definition

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.).

Key characteristics

  1. Constructor name must be the same as the class name
  2. It has no return type (not even void)
  3. It is called automatically when an object is created
  4. Used mainly for initialization

Basic Example

#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;}

Output

Constructor called1

👉 As soon as s1 is created, the constructor runs automatically.

Types of Constructors in C++

1. Default Constructor

A constructor with no parameters.

class Test {public: Test() { cout << "Default Constructor"; }};

Used when you simply write:

Test t;

2. Parameterized Constructor

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.

3. Copy 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 called

4. Constructor Overloading

Multiple constructors in the same class (different parameters).

class Example {public: Example() { cout << "Default\n"; } Example(int a) { cout << "Parameterized\n"; }};

Why Constructors Are Important

✔ Automatically initialize objects✔ Reduce coding errors✔ Used in Object-Oriented Programming for proper setup✔ Helps in resource management✔ Makes code cleaner and safer

< PrevNext >