×

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object. In C++, the function Object () is referred to as a class or structure.

What distinguishes constructors from regular member functions?

  • The function Object () { [native code] } has the same name as the class.
  • Default although constructors do not have an input argument, Copy and Parameterized do. Input parameters are sent to constructors.
  • There is no return type for constructors.
  • When an object is formed, the function Object() { [native code] } is automatically invoked.
  • It must be shown in the classroom's public area.
  • If a function object () {[native code] is not specified, the C ++ compiler creates the default function object () {[native code] for the object (no parameters are expected and the body is empty).cpp-constructor1.png
C++ Constructor

Types of Constructor in C++

  • Default constructor
  • Parameterized constructor
  • Copy Constructor

Default Constructor

Constructors that take no arguments are called default constructors. When creating an object.

Example of a program containing constructor in C++:

#include <bits/stdc++.h>
#include <iostream>
using namespace std;
class construct
{
public:
int i,j; 
// Default Constructor
construct()
{
i= 23;
j= 45;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct k
cout << "i: " << k.i << endl
<< "j: " << k.j;
return 1;
}

OUTPUT:

i: 23
j: 45

Explanation:

Even if we don't explicitly declare a function Object (), the compiler will offer a default function Object() implicitly.

Parameterized constructor

Arguments can be sent to the constructor. These parameters are often used to help start an object when it is created. Just add arguments to the parameterized function object (). The same way you would for any other task. Use arguments to initialize the object while defining the main body of the constructor.

Example of a program containing parameterized constructor in C++:

#include <stdlib>
#include <bits/stdc++.h>
#include <iostream>
using namespace std; 
class Const
{
private:
int i, j;




public:
// Parameterized Constructor
Const(int i1, int j1)
{
i = i1;
j = j1;
}
int getI()
{
return i;
}
int getJ()
{
return j;
}
};
int main()
{
// Constructor called
Const C1 (23, 34); 
// Access values assigned by constructor
cout << "C1.i = " << C1.getI() << ", C1.j = " << C1.getJ();
return 0;
}

OUTPUT:

 C1.i = 23 , C1.j = 34

Explanation:

The initial values must be passed as arguments to the function Object (). Function when an object is declared in a parameterized function Object (). It's possible that the standard method of object definition won't work. Constructors can be invoked either explicitly or implicitly.

NOTE: When objects are formed, it is used to initialize the various data components with distinct values. It's used to make constructors overloaded.

IMPORTANT: We can have more than one constructor in a class.

Copy Constructor

A copy function Object () is a member function that uses another object of the same class to initialize an object. When we declare one or more non-default constructors (with arguments) for a class, we need additionally provide a default constructor (without parameters), as the compiler will not give one in this situation. It is not required, but it is regarded best practice to declare a default function Object () at all times.

Example of program containing copy constructor in C++:

#include <iostream>
#include <stdlib>
#include <bits/stdc++.h>
using namespace std; 
class Const
{
private:
double i, j; 
public: 
// Non-default Constructor &
// default Constructor
Const (double Ci, double Cj)
{
i = Ci, j = Cj;
}
};
int main(void)
{
// Define an array of size
// 10 & of type point
// This line will cause error
Const x[26]; 
// Remove above line and program
// will compile without error
Const y = Const(1, 4);
}

OUTPUT:

error: point (double Ci, double Cj): expects 2 arguments, 0 provided

Explanation

In the above program in C++, If a new item is produced as a copy of an existing item, a copy maker is requested.

Another Example:

#include<iostream>
#Inlcude<stdlib>
#include<bits/stdc++.h>
using namespace std; 
class const
{
int i, j;
public:
const (int x = 14, int y = 34 )
{
i = x;
j = y;
}
void Display()
{
cout<< i << " " << j << endl;
}
};
int main()
{
const val;
val.Display();
return 0;
}

OUTPUT:

Parameterized constructor (Output will be 14,34)

Explanation:

The compiler does not produce the default function Object (). When we define any function Object () in a class. In this scenario, the same thing happens, but because the parameterized function Object () has default values for all of the parameters, it is called. However, if you specify default function Object () here, the compiler will throw an error (ambiguous call) since it won't know which function Object () to call.


Related Topics

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

Hello World Program in C++

The steps for “Hello World” C++ program are as follows: Write a C++ code given below in an editor. Save the file with .cpp Compile the code using C++ compiler or using online...

3 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

How to Reverse a String in C++ using Do-While Loop

Strings In C++, a string is an object that represents a group (or sequence) of various characters. Strings are part of the standard string class in C++ (std::string). The characters of...

4 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

Program that produces different results in C and C++

Introduction: There are many such programs that compile run both in C and C++ but give different outcomes when compiled by the C and C++ compilers. There are a variety of such...

6 minutes read.

Lexicographically Next Permutation in C++

In this tutorial, we'll look at how to use C++ to generate the lexicographically next permutation of a string. The lexicographically next permutation is the larger permutation. "ACB," for example,...

3 minutes read.

Floating Point Operations and Associativity in C, C++ and Java

In this tutorial, we are going to compare Floating-point operations and the concept of associativity. Before we apply the concept of associativity in the floating-point operations in all three programming...

3 minutes read.

C++ Memory Management

Memory management is a method of controlling computer memory and allocating memory space to applications to increase overall system performance. What is the purpose of memory management? Because the array contains homogeneous...

4 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

4 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.