Constructors in C++ Programming

Constructors are the member functions that are executed automatically when an object is created. That means no explicit call is necessary to call a constructor. The name constructor is given because it constructs the value of the data member of class. Constructors are mainly used or initializing data.

Syntax of Constructors

classname ([parameter]) 
{
           body of constructor
}

Types of constructor

  1. Default Constructor: The constructor that accepts no parameters and reserves memory for an object is called default constructor. If no any constructor are explicitly defined then the compiler itself supplies a default constructor.
  2. User defined constructor:The constructor that accepts parameter to initialize the data members of an object are called user defined constructor. Programmer has to explicitly define such constructor in the program.
  3. Copy Constructor: Constructor having object reference as parameter is called copy constructor. A copy constructor when called, creates an object as an exact copy of another object in terms of its attribute. Copy constructor can be called by passing object as parameter or using assignment operator.

Characteristics of constructor

  • Constructor name is same as class name.
  • They should be declared or defined in public section of class.
  • They don’t have any return type like void, int, etc and therefore can’t return values.
  • They can’t be inherited.
  • They are the first member function of a class to be executed.

An example to demonstrate how different types of constructors are created and called:

#include <iostream>
#include <cstring>
#include <conio.h>
using namespace std;
class student
{
 private:
    int roll;
    char name[50];
 public:
    student()  // default constructor
    {
        roll = 0;
        strcpy(name," ");
    }
    student(char n[50], int r)  // user defined constructor
    {
        roll = r;
        strcpy(name,n);
    }
    student(student &s)  // copy constructor
    {
        roll = s.roll;
        strcpy(name,s.name);
    }
    void display()
    {
        cout <<"Name : "<<name<<endl;
        cout <<"Roll : "<<roll<<endl;
    }
};
int main()
{
    student s1;  // call default constructor
    student s2(5,"John");  // call user defined consructor
    student s3(s1);  // call copy constructor
    cout <<"Display value of s1"<<endl;
    s1.display();
    cout <<"Display value of s2"<<endl;
    s2.display();
    cout <<"Display value of s3"<<endl;
    s3.display();
    s3=s2;  // call copy constructor
    cout <<"Display value of s3"<<endl;
    s3.display();
    getch();
    return 0;
}