C++ Constructors


C++ Constructors
A constructor is a member function is can be used to initialize data members.
  • It must be public member function.
  • It must be named the same as the class.
  • It must be no return type. Not even void.
  • Constructor is automatically called when an object of the class is created.
  • It is created by parenthesis (). 
  • The constructor functions have the same name as that of the class name.
  • Mayor may not have parameters
Syntax– Constructor declaration
class Square
    . . .
Square(int s)
   side = s;
 }. . .
Declaration outside 
the class:
Square(int); //prototype
             //in class
Square::Square(int s)
    side = s;

Types of constructor
There are three types of constructors are as follows:
  1. Default Constructor
  2. Parameter Constructor
  3. Copy Constructor

1.Default Constructor: Because in C++ Default Constructor, This constructor has no argument. A default constructor is also called a no-argument constructor. 

the Default argument is an argument to a function that a programmer is not required to specify.
C++ allows the programmer to specify default arguments that always have, even if one is not specified when calling the function.
For example, in the following function declaration:
2.Parameter Constructor: A parameterized constructor is just one that has parameters specified in it.
  • We can pass the arguments to constructor function when objects are created.
  • A Constructor that can take arguments are parameterized constructors.
For example, in the following function declaration:
3.Copy Constructor
Copy constructor is used declare and initialize an object from another object.
  • For example: abc c2(c1)
  • Would define the object c2 and at the same time initializing it to the value c1.
  • The process of initializing through a copy constructor is known as copy initialization.
For example, in the following function declaration:

class A  
    A(A &x) //  copy constructor.  
       // copyconstructor.