Constructor in C++ and Types of Constructors (2023)

Table of contents

      • What is Constructor in C++?
        • Constructor in C++ Syntax
      • Types of Constructors in C++
      • Default Constructor
      • Parameterized Constructor
      • Copy Constructor in C++
      • Constructor Overloading
      • Constructor in Array of Objects
      • Work Double Pointer
      • Using a New Keyword
      • Constructor with Default Arguments
      • Initializer List
      • Dynamic Initialization using Constructor
      • Constructor in C++ FAQs

What is Constructor in C++?

A constructor in C++ is a special ‘MEMBER FUNCTION’ having the same name as that of its class which is used to initialize some valid values to the data members of an object. It is executed automatically whenever an object of a class is created. The only restriction that applies to the constructor is that it must not have a return type or void. It is because the constructor is automatically called by the compiler and it is normally used to INITIALIZE VALUES. The compiler distinguishes the constructor from other member functions of a class by its name which is the same as that of its class. ctorz is an abbreviation of constructor in C++.

C++ constructor can be defined as aclass in the same way as that of normal member functions and can access any of its data members.

  • What is a Constructor in C++?
  • Types of Constructors in C++
    • Default Constructor
    • Parameterized Constructor
    • Copy Constructor in C++
  • Constructor Overloading
  • Constructor in Array of Objects
  • Work Double Pointer
  • Using a New Keyword
  • Constructor with Default Arguments
  • Initializer List
  • Dynamic Initialization using Constructor
  • Constructor in C++ FAQs

Constructor in C++ Syntax

The syntax for defining constructor inside the class body is as follows:

class CLASSNAME{ ……… public : CLASSNAME([parameter_list]) // constructor definition { . . . . . . } . . . . . . . .};

You can also define a constructor with its declaration inside the class body and see what follows.

class CLASSNAME { . . . . . . . . public: CLASSNAME ([parameter_list]);//Constructor declaration . . . . . . . . .}; CLASSNAME: :CLASSNAME([parameter_list])//Constructor Definition{. . . . . . . . . . .}
  • The above syntax shows the declaration and definition of a constructor. It is defined outside the class in the same way as we define a member function outside the class using the scope resolution operator.
  • One should note that the name of the constructor is the same as that of its class. The constructor parameter list enclosed in the square brackets is optional and may contain zero or more parameters.
  • We should declare the constructor in the public section of the class as they are invoked automatically when the objects are created.

With the help of examples, we will learn about the C++ constructor and its type in this article.

When an object is created, a particular kind of member function called a constructor is immediately invoked.

A constructor in C++ does not have a return type and shares the same name as the class. For instance,

class Table{ Public: Table(){ }};

Here, the purpose The constructor for the class Table is called Table(). Take note that the Constructor.

  • The constructor has the same name as the class.
  • The constructor does not have a return type, and
  • Constructor is public

Types of Constructors in C++

There are 3 types of constructors in C++, They are :

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor
Constructor in C++ and Types of Constructors (1)

Default Constructor

A constructor to which no arguments are passed is called the Default constructor. It is also called a constructor with no parameters.

Constructors are class functions that are called when new instances of the class’s objects are produced. The constructors share the same name as the class, but they don’t even have void as a return type. They are most helpful for giving class variables their initial values. Default constructors and parameterized constructors are the two primary types of constructors.

There are no parameters accepted by default constructors. The compiler will give an implicit default constructor if the programmer does not explicitly provide one. In that scenario, the variables’ default values are 0.

Using the default constructor, data members can be initialized to some realistic values in its definition even though no arguments are specified explicitly. Each time an object is created, a constructor is invoked. If we define objects and classes without defining any constructor for a class. So in such a situation, the compiler automatically generates a constructor of its own without any parameters i.e. Default Constructor.

This compiler generates a default constructor which is invoked automatically whenever any object of the class is created but doesn’t perform any initialization. However, if you define a default constructor explicitly, the compiler no longer generates a default constructor for you.

The following are the key points while defining constructors for a class:

  • A constructor has the same name as that of the class to which it belongs to.
  • If you don’t openly provide a constructor of your own then the compiler generates a default constructor for you.
  • A constructor can preferably be used for initialization and not for input/output operations.
  • Constructors may not be static.
  • Constructors are also used to locate memory at run time using the new operator.
  • Constructors cannot be virtual.
  • A constructor is executed repeatedly whenever the objects of a class are created.
  • We can declare more than one constructor in a class i.e. constructors can be overloaded.

Program on Default Constructor

class Line{ public: int size;//default constructorLine(){ size=30;}};int main(){ //default constructor called when object is created Line l; cout<<"Line size is"<<" "<<l.size<<" "<<"cm";return 0;}
OutputLine size is 30 cm

The constructor for the code above is invoked as soon as the object is created to initialise its data members.

In the example above, we have provided the no argument default constructor Line(); however, if we don’t, the compiler will supply it to aid in initialising the data members.

Example:

#include <iostream>using namespace std;class TestDefault { private: int num1, num2 ; public: TestDefault() { num1 = 10; num2 = 20; } void display() { cout<<"num1 = "<< num1 <<endl; cout<<"num2 = "<< num2 <<endl; }};int main() { TestDefault obj; obj.display(); return 0;}
Outputnum1 = 10num2 = 20

Parameterized Constructor

Unlike default constructors which do not take any parameters, it is however possible to pass one or more arguments to a constructor.

Constructors that can take arguments are known as parameterized constructors.

The syntax for declaring parameterized constructor inside the set:

class class_name {public: class_name(variables) //Parameterized constructor declared. { }};

The syntax for declaring parameterized construct outside the class:

class class_name{ };class_name :: class_name() //Parameterized constructor declared.{ } 

Copy Constructor in C++

The copy constructor in c++ is a constructor that creates an object by initialising it with a previously created object of the same class.

Constructor Overloading

In some programs, a class had only one constructor which was either zeroes, one, or more parameters. The constructor is key for object initialization. The mechanism of the constructor is made considerably more powerful by uniting with the feature of overloading. It is made possible by providing more than one constructor in a class called Constructor overloading.

C++ Constructor Overloading Example

/*.....A program to feature the concept of constructor overloading.......... */#include <iostream>using namespace std;class ABC{ private: int x,y; public: ABC () //constructor 1 with no arguments { x = y = 0; } ABC(int a) //constructor 2 with one argument { x = y = a; } ABC(int a,int b) //constructor 3 with two argument { x = a; y = b; } void display() { cout << "x = " << x << " and " << "y = " << y << endl; }};int main(){ ABC cc1; //constructor 1 ABC cc2(10); //constructor 2 ABC cc3(10,20); //constructor 3 cc1.display(); cc2.display(); cc3.display(); return 0; } //end of program
OUTPUT:X = 10 and y = 0X = 10 and y = 10x = 10 and y = 2

Constructor in Array of Objects

Constructors are called for every object of a class being created. Whenever an array of class objects is defined then a default constructor is called for each object of the array.

In other words, each object of the array is initialized with the same set of values using the default argument constructor.

For example:

rectangle r[20];

It defines an array of 20 objects of the class rectangle. Each object (element) of the array rectangle invokes the default constructor for initializing its data members. We can also initialize the value to individual objects of an array explicitly using the parameterized constructor which is shown below:

rectangle r[3]={rectangle(5,6),rectangle(7,8),rectangle(5,7)};

Three objects r[0], r[1], r[2] are created and initialized using the constructor with two parameters as only two arguments are passed. Here, the constructor with a two-parameter is called explicit for initializing individual objects of the array.

Initialize Array of objects with parameterized constructors in C++

When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to build objects to use the data and access functions specified in the class.

Syntax:

123

Specific methods for initializing the Parameterized Constructors list of objects:

Using malloc(): Use the malloc() method to avoid calling a non-parameterized constructor. The “Malloc” or “Memory Allocation” method in C++ is used to dynamically allocate the specified size of a single large block of memory. It returns a sort of void pointer that can be thrown into a pointer of any kind.

#include <iostream>#define P 5using namespace std;class Test{ // private variables int a, b;public: // parameterized constructor Test(int a, int b) { this->a = a; this->b = b; } // function to print void print() { cout << a << " " << b << endl; }};int main(){ // allocating dynamic array // of Size N using malloc() Test* arr = (Test*)malloc(sizeof(Test) * P); // calling constructor // for each index of array for (int k = 0; k < P; k++) { arr[k] = Test(k, k + 1); } // printing contents of array for (int k = 0; k < P; k++) { arr[k].print(); } return 0;}
Output:0 1 1 2 2 3 3 4 4 5

Work Double Pointer

  • The pointer to a pointer is a set of complex indirect or a pointer chain. A pointer often holds the address of a variable. When we narrate a pointer to a pointer, the first pointer contains the second pointer‘s address, which points to the location containing the real value, as shown below.
  • Now we can allocate a number of blocks to be assigned, so we have to call the parameterized constructor to initialize for each index using the new keyword.
#include <iostream>#define T 10using namespace std;class Test { // private variables int s, t;public: // parameterized constructor Test(int s, int t) : s(s), t(t) { } // function to print void print() { cout << s << " " << t << endl; }};int main(){ // allocating array using // pointer to pointer concept Test** arr = new Test*[T]; // calling constructor for each index // of array using new keyword for (int i = 0; i < T; i++) { arr[i] = new Test(i, i + 1); } // printing contents of array for (int i = 0; i < T; i++) { arr[i]->print(); } return 0;}
Output:0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10

Using a New Keyword

On the Heap, the new operator denotes a memory allocation request. If there is enough memory, the new operator identifies the memory and returns the newly allocated and configured memory address to the variable name.

Here, point variable is the information-type pointer. Data type could be any type of built-in data along with an array or any type of user-defined data such as structure and class.

If we add a parameterized constructor, a new keyword requires a non-parameterized constructor for dynamic initialization. So we’re going to use a dummy constructor for that.

#include <iostream>#define E 15using namespace std;class Test { // private variables int m, n;public: // dummy constructor Test() {} // parameterized constructor Test(int m, int n) { this->m = m; this->n = n; } // function to print void print() { cout << m << " " << n << endl; }};int main(){ // allocating dynamic array // of Size N using new keyword Test* arr = new Test[E]; // calling constructor // for each index of array for (int j = 0; j < E; j++) { arr[j] = Test(j, j + 1); } // printing contents of array for (int j = 0; j < E; j++) { arr[j].print(); } return 0;}
Output:0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 11 12

Constructor with Default Arguments

By defining constructors with default arguments, this facility allows a constructor called to specify the fewer number arguments instead of passing all the arguments defined in the constructor. If the constructor called during object creation, doesn’t specify all the arguments then the omitted arguments can take default values specified in the constructor definition.

However, if the constructor is declared inside and defined outside the class then default values are provided in the constructor declaration and not in its definition.

When the constructor call specifies the arguments corresponding to the default arguments then the past arguments always override the default values.

Constructors with default arguments may help to reduce the size of the class as there is no need to make multiple constructors in the class. This can be seen by comparing the above program with the previous program of the complex number.

However, in certain situations, if it is likely that the default arguments value will change then it is better to use an overloaded constructor instead of a single constructor with default arguments.

Initializer List

C++ provides an alternative syntax for initializing data members of the objects in the constructor known as Initialize list. A rectangle constructor with two parameters can be rewritten to use the initializer list is as follows: rectangle(int a, int b): length(a), breath(b) {. . . }

The initialize list is placed between the parameters list and the opening brace of the body of the constructor. The list begins with the colon(:)and is separated by commas.
Each initialize clause simply names the data members and in the parentheses lists the value to be used to initialize the data member.

When the constructor is declared inside and defined outside the class using scope resolution operator then the member initialization list can only be specified within the constructor definition and not in its declaration. An initialize list allows the initialization of data members at the time of their creation which is more efficient as values are assigned before the constructor even starts to execute.

Dynamic Initialization using Constructor

Data members of an object after creation can be initialized at run time using constructors. Such initialization of data members is called dynamic initialization.

The main advantage of dynamic initialization is the ability to allow different modes of initialization using overloaded constructions. Hence, the user can provide different formats of data depending on the requirement.

Consider an example of displaying the height of a person in feet and inches.
The different formats for specifying the height of a person can be 5 feet, 5.5 feet, and explicitly specifying like 5 feet and 8 inches.

#include<iostream.h>#include<conio.h>Class height{ Private: Int feet: Double inches; Public: Height(int f) { Feet=f; Inches=0.0; } Height(double f) { Feet=int(f); Inches=(f-int(f))*12.0; } Height() { Feet=inches=0; } Height(int f, double in) { Feet=f; inches=in; } Void show() { Cout<<”feet=”<<feet<<” inches=”<<inches<<endl; }}://end of class specificationInt main(){ Clrscr(); Height h1, h2, h3;// default constructor invoked Int ht_feet; Cout<<”Enter height in term of feet only :”; Cin<<ht_feet; H1 = height(ht_feet); Double ht_ fract; Cout<<”Enter height in terms of feet in fractional forms : “; Cin>>ht_fract; H2= height(ht_fract); Int ft1; Double in1; Cout<<”Enter height in terms of feet and inches : “ ; Cin>>ft1>>in1; H3 = height(ft1, in1; H1.show(); h2.show(); h3.show(); Getch(); return 0;}
OUTPUT:Enter height in terms of feet only: 5Enter height in terms of feet in the fractional form: 5.5Enter height in terms of feet and inches: 5 8 Feet = 5 Inches = 0Feet = 5 Inches = 6Feet = 5 Inches = 8

Explanation:

In this program, we have four constructors. The arguments to the parameterized constructors are provided at run time. The user can specify the height of a person in any of the following formats:

  • Not specifying any height and hence default constructor is invoked which initialize feet and inches to 0 each.
  • Specifying height only in terms of feet in integral form and for this constructor height(int); is invoked.
  • Specifying height only in terms of feet in fractional form and for this, constructor height(double); is invoked.
  • Specifying height in inches, constructor height(int, double); is invoked.

The constructor height ()is overloaded and which one will be called depends on the arguments specified by the constructor.

This brings us to the end of the blog on Constructor in C++. We hope that you were able to gain some knowledge from the same. If you wish to learn more about such concepts as constructor in C++ or any other programming language, you can join Great Learning Academy’s Free Online Courses today.

Constructor in C++ FAQs

What is a constructor in CPP?

When an object is created in C++, a special method called the constructor is immediately called. In general, it is utilised to initialise new objects’ data members. In C++, the class or structure name serves as the name of the constructor { [native code] }. When creating an object, the constructor is called. It creates the values, i.e., supplies the object with data, which is why it is referred to as a constructor { [native code] }.

Because a constructor does not have a return value, it lacks a return type.

The following are some differences between constructors and regular functions:

The class’s name is also used for the constructor { [native code] }.
While Copy and Parameterized Constructors do have input arguments, Default Constructors do not.
Return types do not exist for constructors.
When an object is formed, a constructor is automatically invoked.
It must be shown in the classroom’s open area.
The C++ compiler creates an object’s default constructor if we don’t supply one (expects no parameters and has an empty body).

What is constructor and its types in C++?

Constructors are class functions that are called when new instances of the class’s objects are produced. The constructors share the same name as the class, but they don’t even have void as a return type. They are most helpful for giving class variables their initial values.

Default constructors and parameterized constructors are the two primary types of constructors. Here are some specifics on these.

Default Constructor:

There are no parameters accepted by default constructors. The compiler will give an implicit default constructor if the programmer does not explicitly provide one. In that scenario, the variables’ default values are 0.

Parameterized Constructor:

When an object is created, the parameterized constructors can accept arguments to initialise it. Similar to adding parameters to a regular function, parameters are added to a parameterized constructor { [native code] }. Both implicit and explicit calls to the parameterized constructors are possible.

What are the 3 types of constructors in cpp?

Default Constructor:

There are no parameters accepted by default constructors. The compiler will give an implicit default constructor if the programmer does not explicitly provide one. In that scenario, the variables’ default values are 0.

Parameterized Constructor:

When an object is created, the parameterized constructors can accept arguments to initialise it. Similar to adding parameters to a regular function, parameters are added to a parameterized constructor { [native code] }. Both implicit and explicit calls to the parameterized constructors are possible.

Copy Constructor:

The copy constructor is used to duplicate an existing object when generating a new object. In C++, it is a common method of copying objects. As an argument, it accepts a reference to an object of the same class.

What is constructor in OOP?

Constructor is a unique method in OOP (object-oriented programming). When you use the new keyword to create an object, it is called each time. An object can initialise itself when it is created using a constrictor, eliminating the need for a second call to the instance function. Although it has the appearance of a technique, it differs from the method in the following two respects.

A constructor’s name is always the same as the class whose members it initialises.
Additionally, it lacks void-like functions and a return type. Every time an object belonging to the class is created, it triggers the compiler to automatically call the constructor { [native code] }.

Why constructor is used in C++?

A constructor is a special “MEMBER FUNCTION” in C++ that has the same name as the class it belongs to and is used to initialise some useful values for an object’s data members. The constructor is used to INITIALIZE VALUES and is automatically called by the compiler, which is why.

Is constructor being a method?

A class’s constructor method is a particular method for constructing and initialising a class-specific object instance.

A particular method called a constructor generates an instance of a class. Typically, constuctor methods receive input arguments to initialise the object and assign the data contained in properties. See Creating a Simple Class for a simple illustration.

What are the types of constructors?

When an object of a class is created in C++, the member functions called constructors are called. In C++, constructors fall into one of three categories: default, parameterized, or copy.

Can we overload constructor?

Similar to function overloading, constructor overloading is a possibility. The class name is the same for overloaded constructors, but they take a different number of parameters. The appropriate constructor is invoked based on the quantity and kind of parameters given.

Why is constructor used?

To initialise the object with the default or starting state, we utilise constructors. Primitive default settings might not be what you’re looking for. Utilizing a constructor also provides information on dependencies.

Top Articles
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated: 12/31/2022

Views: 6509

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.