Types of constructors in C++

Types of constructors in C++

Types of constructors

  1. Copy constructor
  2. Conversion constructor
  3. Default Constructor(also known as Zero argument constructor)
  4. Parameterized constructor
  5. Explicit constructor

Copy Constructor

A copy constructor is a like a normal parameterized Constructor, but in Copy Constructor, the parameter is the class object. In other words we can say that Copy constructor uses to initialize an object using another object of the similar class.

Syntax of Copy Constructor

class class_name {
public:
class_name(class_name & object) {
// object is the  another object of the same class
// Copy Constructor code
}

//… other Variables & Functions
}

When Copy Constructor is called?

Let’s see some scenarios where a copy constructor is called.

  1. When one object is initialized by the user with another existing object of the same class.
  2. When the object of the same class is passed by value as an argument.
  3. Whenever the object of the same class is generally returned by the function.

Types of Copy Constructor

There are two Types of Copy Constructor

  • Default Copy constructor: The compiler defines the default copy constructor. If the user defines no copy constructor, compiler triggers its constructor.
  • User Defined constructor: The programmer defines the user-defined constructor according to its own needs.

C++ Program of Copy Constructor

Conversion constructor in C++

Suppose that a class has a constructor which can be called with a single argument, then this constructor works as conversion constructor. The main reason to called it conversion constructor is  “because such a constructor allows automatic conversion to the class being constructed”.

Conversion constructor C++ Example

Default Constructor

Default constructor is the constructor which doesn’t take any parameter as a value.

Default Constructor C++ Example

Parameterized constructor

Parameterized constructor is a constructor with parameters as a values, it follows all the properties just like a normal constructor and takes parameters into the constructor to initialize the data and that is the reason to called it Parameterized constructor.

Explicit constructor

As we know that Constructors are functions with the same name as the class name. Constructors are used to create the instance of a class. If we don’t make any Constructors  then They are provided by default by the compiler itself. However, the user can also declare and use its own constructor by explicitly declaring the Constructors.

Subscribe for Friendship

Latest posts by Prof. Fazal Rehman Shamil (see all)

Buy advertisement space on T4Tutorials

For more details email [email protected]