Constructor In C++

Introduction

  • It is the special member function of the class.
  • It has the same name of the class.
  • It is automatically called when an object( the instance of the class) create.
  • It must be a public member.
  • No Return Values.

Constructor General Form:

class class-name {
    Access Specifier :
    Member - Variables
    Member - Functions
public:
    class-name()
     {
        // Constructor code
    }
    //... other Variables & Functions
}

Constructor Example Program:

class Example {
    int a, b;
public:
    //Constructor
    Example() {
        a = 10;
        b = 20;
        cout << "Im Constructor"
    }
    void Display() {
        cout << "Values :" << a << "\t" << b;
    }
}

int main() {
    Example Object;
    // Constructor invoked.
    Object.Display()
    return;
}

Sample Output:

10  20


Parameterized Constructor:

  • Which constructor has arguments that is called Parameterized Constructor.

Parameterized Constructor General Form:

class class-name {
    Access Specifier :
    Member - Variables
    Member - Functions
public:
    class-name(type Variable, type Varibale2......) {
        // Constructor code
    }
    //... other Variables & Functions
}

Parameterized Constructor Example Program:

class Example {
    int a, b;
public:
    //Constructor
    Example(int x, int y) {
        a = x;
        b = y;
        cout << "Im Constructor"
    }
    void Display() {
        cout << "Values :" << a << "\t" << b;
    }
}

int main() {
    Example Object(10, 20);
    // Constructor invoked with parameters.
    Object.Display()
    return;
}

Sample Output:

10  20