what is a constructor in c LEARNOVITA

C++ Constructors Tutorial: Types and Copy Constructors

Last updated on 11th Aug 2022, Blog, Tutorials

About author

Boopathy krishna (Software Developer )

Boopathy Krishna is a certified professional with 7+ years of experience in their respective domain. She has expertise in C, C++, Java, Hibernate, and Spring Boot.

(5.0) | 18284 Ratings 2075

What is C++?

  • C++ is also a cross-platform language which will be accustomed turn out superior applications.
  • C++ was developed by Bjarne Stroustrup, as Associate in Nursing extension to the C language.
  • C++ provides programmers a high level of management over system resources and memory.
  • The language was updated four major times in 2011, 2014, 2017, and 2020 to C++11, C++14, C++17, C++20.

Why Use C++?

  • C++ is one altogether the world’s preferred programming languages.
  • C++ are found in today’s operative systems, Graphical User Interfaces, and embedded systems.
  • C++ is Associate in Nursing object-oriented artificial language that provides a clear structure to programs and permits code to be reused, lowering development costs.
  • C++ is transportable and should be accustomed develop applications which will be bespoke to multiple platforms.
  • C++ is fun and straightforward to learn.
  • As C++ is on the purpose of C, C# and Java, it makes it straightforward for programmers to switch to C++ or the opposite method around.

C++ constructor

In C++, creator is also a special technique that’s invoked automatically at the time of object creation. It’s accustomed initialize the data members of latest object typically. The creator in C++ has constant name as class or structure.

Constructor Parameters:

Constructors also can take parameters (just like regular functions), which might be helpful for setting initial values for attributes.The following category have whole, model and year attributes, and a creator with totally different parameters. within the creator we have a tendency to set the attributes adequate to the creator parameters (brand=x, etc). after we decision the creator (by making associate object of the class), we have a tendency to pass parameters to the creator, which is able to set the worth of the corresponding attributes to the same:

Prerequisites

You’ll need the following to read this article through:

  • A working knowledge of the C++ language.
  • A working knowledge of C++ functions.
  • To run the code, use the Codeblocks IDE.

Types of constructors in C++.

  • Default constructor
  • Parameterized constructor
  • Copy constructor

Default constructor:

A creator that has no argument is thought as default creator. it’s invoked at the time of making object.

  • :#include <"iostream">
  • :using namespace std;
  • :class Employee
  • :{
  • :public:
  • :Employee()
  • :{
  • :cout<<"Default Constructor Invoked"endl;
  • }
  • };
  • :int main(void)
  • :{
  • :Employee e1;//creating an object of Employee
  • :Employee e2;
  • :return 0;
  • :}
  • :Output:
  • :Default Constructor Invoked
  • :Default Constructor Invoked

Parameterized constructor:

A builder that has parameters is termed parameterized builder. it’s wont to give totally different values to distinct objects.

Let’s see the simple example of C++ Parameterized Constructor.

  • #include <"iostream">
  • using namespace std;
  • class Employee {
  • public:
  • int id;//data member (also instance variable)
  • string name;//data member(also instance variable)
  • float salary;
  • Employee(int i, string n, float s)
  • {
  • id = i;
  • name = n;
  • salary = s;
  • }
  • void display()
  • {
  • cout<<"id name" "salaryend"l;
  • }
  • };
  • nt main(void) {
  • Employee e1 =Employee(101, “Sonoo”, 890000); //creating an object of Employee
  • Employee e2=Employee(102, “Nakul”, 59000);
  • e1.display();
  • e2.display();
  • return 0;
  • }
  • Output:
  • 101 Sonoo 890000
  • 102 Nakul 59000

Copy Constructor:

A copy constructor could be a member operate that initializes Associate in Nursing object mistreatment another object of constant category. an in depth article on Copy builder.Whenever we tend to outline one or additional non-default constructors( with parameters ) for a category, a default builder( while not parameters ) ought to even be expressly outlined because the compiler won’t give a default constructor during this case. However, it’s not necessary however it’s thought of to be the most effective follow to invariably outline a default builder.Copy builder takes a respect to Associate in Nursing object of constant category as Associate in Nursing argument.

  • #include <"iostream">
  • using namespace std;
  • class A
  • {
  • public:
  • int x;
  • A(int a)// parameterized constructor.
  • {
  • x=a;
  • }
  • A(A &i)// copy constructor
  • {
  • x = i.x;
  • }
  • };
  • int main()
  • {
  • A a1(20);// Calling the parameterized constructor.
  • A a2(a1);// Calling the copy constructor.
  • couta2.x;
  • return 0;
  • }
  • Output:
  • 20

Characteristics of Constructor:

  • The name of the creator is that the same as its category name.
  • Constructors ar principally declared within the public section of the category it may be declared within the personal section of the category.
  • Constructors don’t come back values; thence they are doing not have a come back sort.
  • A creator gets referred to as mechanically after we produce the item of the category.
  • Constructors may be full.
  • Constructor can’t be declared virtual.

Multiple constructors:

C++ allows us to use the three constructor functions we have discussed in the same class.

For example:

  • class complex
  • {
  • int a, b;
  • public:
  • complex() // default constructor
  • {
  • a= 10;
  • b=45;
  • };
  • complex( int x, int y) // parameterized constructor
  • {
  • a=x;
  • b=y;
  • };
  • complex( complex & v) // copy constructor
  • {
  • a=v.a;
  • b=v.b;
  • };
  • }

Because no values were given by the calling programme to the first function Object() function, the function Object() assigned the data values to itself.The main function’s proper values are passed as parameters to the second function Object() function by the function call.The third function Object() function’s arguments are objects. The values of the first data element are set to their appropriate values by copy constructors.

Constructor-based Dynamic Initialization

After an object is created, its data members can have their initial values set at runtime using constructors. Dynamic initialization is the term for this type of data member initialization.The flexibility to support several initialization methods utilising overloaded constructions is the primary benefit of dynamic initialization. As a result, the user can supply data in various formats based on the request.Think about an illustration showing a person’s height in feet and inches.The various methods for expressing a person’s height include 5 feet, 5.5 feet, and expressly stating something like 5 feet and 8 inches.

Program:

  • #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=” "inches=”endl;
  • }
  • }://end of class specification
  • Int main()
  • {
  • Clrscr();
  • Height h1, h2, h3;// default constructor invoked
  • Int ht_feet;
  • Cout<<”Enter height in term of feet only :”;
  • Cinht_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: 5
  • Enter height in terms of feet in the fractional form: 5.5
  • Enter height in terms of feet and inches: 5 8
  • Feet = 5 Inches = 0
  • Feet = 5 Inches = 8

Explanation:

There are four constructors in this programme. The parameterized constructors receive their parameters at runtime. A person’s height can be entered in any of the following formats by the user:

  • There is no height specified, therefore the default function Object() is used, which sets the feet and inches to 0 for each.
  • Using the function Object() height(int); and only specifying height in feet in integral form.
  • Only specifying height in fractional feet, in which case the function Object() height(double); is used.
  • The function Object() height(int, double); is used to specify height in inches.
  • The arguments provided by the function Object() determine which of the overloaded constructors height () will be called.

Important of Constructors in C++

An object’s function is called immediately upon creation and must be declared in the public part of the class.They are unable to return values and lack return types.It might use default arguments.We are unable to use their address.

Are you looking training with Right Jobs?

Contact Us

Popular Courses