Constructors in C++

05 min read

Constructors: Constructors are special class functions which perform initialization of every object. Constructor’s initialize values to object members after storage is allocated to the object.

Syntax:

class A
{
 int x;
 public:
 A();  //Constructor
};

 

Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution :: operator.

Example:

class A
{
 int i;
 public:
 A(); //Constructor declared
};
A::A()   // Constructor definition
{
 i=1;
}

 

Types of Constructors:  Constructors are of three types:

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor

1) Default Constructor: Default constructor is the constructor which doesn't take any argument. It has no parameter.

Syntax

class_name ()
{
Constructor Definition
}

Example:

Class Cube
  {
  int side;
  public:
  Cube() // constructor declaration
  {
  side = 10;
  }
  };

  int main()
  {
  Cube c;
  cout << c.side;
  }

 

2) Parameterized Constructors: These are the constructors with a parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as an argument.

Example:

Class Cube
  {  
  int side;
  public:
  Cube ( int x)
  {
  side = x;
  }
  };

  int main()
  {
  Cube c1(10);
  Cube c2(20);
  cout << c1.side;
  cout << c2.side;
  }

 

3) Copy Constructor: These are the special type of Constructors which takes an object as an argument, and is used to copy values of data members of one object into another object.

Syntax

class-name (class-name &)
{
 . . . .
}

Copy Constructor is a type of constructor which is used to create a copy of an already existing object of a class type. It is usually of the form X (X&), where X is the class name. The compiler provides a default Copy Constructor to all the classes.

# include < iostream>
Using namespace std;
class Code;
{
  int id;
  public:
  code () // constructor
{
}
 
code ( int a) // constructor again
{
   id = a;
}

code ( code &x) // copy constructor
{
id = x. id;
}

void display ( void)
{
cout << id;
}
};

int main()
{
  Code A(100);
  Code B(A); //copy constructor called
  Code  C  = A; // copy  constructor called
  Code D;
  D = A;
  cout << “ id of A is : “ << A. display();
  cout << “ id of B is : “ << B. display();
  cout << “ id of C is : “ << C. display();
  cout << “ id of D is : “ << D. display();
  return 0;
}

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error