Ask a Teacher
what are the types of constructors & when it used? |
A constructor (sometimes shortened to ctor) in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created. It is called a constructor because it constructs the values of data members of the class. Constructor:- 1) Constructor is used for Initializing the values to the data members of the Class. 2) Constructor is that whose name is same as name of class. 3) Constructor gets Automatically called when an object of class is created. 4) Constructors never have a Return Type even void. 5) Constructor are of Default , Parameterized and Copy Constructors. The various types of Constructor are as follows:- Default Constructor:- Default Constructor is also called as Empty Constructor which has no arguments and It is Automatically called when we creates the object of class but Remember name of Constructor is same as name of class and Constructor never declared with the help of Return Type. Means we cant Declare a Constructor with the help of void Return Type. , if we never Pass or Declare any Arguments then this called as the Copy Constructors. Parameterized Constructor :- Constructors that can take arguments are termed as parameterized constructors. The number of arguments can be greater or equal to one(1). Copy Constructor:- Copy constructors define the actions performed by the compiler when copying class objects. A copy constructor has one formal parameter that is the type of the class (the parameter may be a reference to an object). In this Constructor we pass the object of class into the Another Object of Same Class. As name Suggests you Copy, means Copy the values of one Object into the another Object of Class .This is used for Copying the values of class object into an another object of class So we call them as Copy Constructor and For Copying the values We have to pass the name of object whose values we wants to Copying and When we are using or passing an Object to a Constructor then we must have to use the & Ampersand or Address Operator. |