Constructor In C++ With Example

Card image cap

Constructor?

Constructor is a special member function of a class that is executed whenever we create new objects of that class.


It is used to initialize the data members of new object generally.
The constructor in C++ has the same name as class or structure.

There can be two types of constructors in C++.

  1) Default Constructor
2) Parameterized constructor

Constructor doesn’t have a return type.

Constructor is automatically called when we create the object of the class.

Member function needs to be called explicitly using object of class.


Card image cap

Default Constructor?

Default constructor is the constructor which doesn’t take any argument. It has no parameters.

In practical programs, we often need to initialize the various data elements of the different object with different values when they are created. This can be achieved by passing the arguments to the constructor functions when the object is created.

Note: Even if we do not define any constructor explicitly, the compiler will automatically provide a default constructor implicitly.

Default Constructor Syntax:

     /*.....format of default constructor..........*/
 class class_name
 {
 	.........
 	public:
 	class_name() { }; //default constructor
 	.........
 };
Card image cap

Example :



Output :

 Welcom to aimtocode
 Welcom to aimtocode


Card image cap

Parameterized Constructor

Constructors with parameters are known as Parameterized constructors. It is used to provide different values to distinct objects.

A default constructor does not have any parameter, but if you need, a constructor can have parameters. This helps you to assign initial value to an object at the time of its creation as shown in the following example.

Example :



Output :

 Object is being created, length = 10
 Length of line : 10
 Length of line : 6
      
Card image cap