×

Constructor Vs Destructor in C++

C++ Constructor

A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is generated.

class Name  // syntax
{  
……….  
public  
Name ([parameter list])  
{  
……………….  
}  
};

Explanation:

The constructor's name is class name, the public specifier is an access specifier, and the parameter list is optional in the above syntax.

Example of a program showing the use of constructor in C++:

#include <iostream.h>  
#include <bits/stdc++.h>
#include <stdlib>
#include <conio.h>  
using namespace std;  
class First_hello {     // The class  
  public:           // Access specifier  
   first_hello () {     // Constructor  
      cout << "Hello World! Program in C++ showing the use of Constructor";  
    }  
   void display() {  
     cout <<"Hello World!" <<endl;  
   }  
};  
int main() {  
  hello myObje;   /  
  return 0;  
}  

OUTPUT:

Hello World!

Types of Constructor available in C++

  1. Default constructor
  2. Dynamic constructor
  3. Parameterized constructor
  4. Copy constructor

Default Constructor

A default function Object () { [native code] } is a function Object() { [native code] } that does not accept any parameters. If a class doesn't have a function Object () { [native code] }, the compiler constructs one for it implicitly.

class name {  //syntax
private:  
………..  
………..  
public:  
name ()  
{  
…….  
}  
} 

Explanation:

There are no arguments or parameter lists in this sort of function Object () { [native code] }. The compiler constructs the class's default function Object () { [native code] } if no function Object() { [native code] } is defined in the class.

Parameterized Constructor

A parameterized function Object() { [native code] } is a type of function Object() { [native code] } that can accept parameters. It's used to provide objects a separate set of values when they're created.

Class Name  //syntax
{  
…………;  
…………;  
Public:  
Class Name (parameter list)  
{  
………….;  
}  
};

Explanation:

The constructor's parameter list can be defined here.

Copy Constructor

A function Object () { [native code] } that is used to create a new object from an existing one. The copy function Object () { [native code] } is used to copy data from another object of the same type.

Class (Name, &object)  //syntax
{  
………….;  
………….;  
}  

Explanation:

The object in the above syntax refers to an item that is utilized to initialize another object.

Dynamic Constructor

This function Object () { [native code] } can be used to allocate memory for objects while they are being created. Dynamic initialization is the process of initializing the data members of an object after it has been created.

C++ Destructor

The same class name prefixed by the () tilde symbol is used for destructors. It removes and destroys the object's memory, which was allocated by the function Object () { [native code] } during its creation.

class Name  //syntax
{  
…………….;  
…………….;  
public:  
abc();            //constructor  
~abc();           //destructor  
};

Explanation:

In C++ programming, the tilde symbol is used to define the destructor. Because the Destructor takes no arguments and returns no value, it cannot be overloaded.

Example of a program showing the use of destructor in C++:

#include <iostream.h>  
#include <bits/sdtc++.h>
#include <stdlib>
#include <conio.h>  
using namespace std;  
class Helloworld {  
public:  
  //Constructor  
  Helloworld () {  
    cout<< "Constructor function is called" <<endl;  
  }  
  //Destructor  
  ~Helloworld () {  
    cout << "Destructor function is called" <<endl;  
   }  
   //Member function  
   void display() {  
     cout <<"Hello World!" <<endl;  
   }  
};  
int main(){  
   //Object created  
   Helloworld obje;  
   //Member function called  
   obje.display();  
   return 0;  
}  

OUTPUT:

Hello World!
…………………….
Process exited with return value 0
Press any key to continue.

In C++ programming, there is a distinction between constructors and destructors as follows:

CharacteristicsConstructor in C++Destructor in C++
MotiveIn C++, we used a function Object () {[native code]} to allocate memory to the object.In C++, we use the concept of destructor to de-allocate the memory that the function Object () { [native code] } allocated to an object for this purpose.
ArgumentsIt could include or exclude arguments.It is unable to accommodate the arguments.
CallingIt is invoked automatically whenever a class object is generated.When the application ends, it automatically calls this function.
RAMThe function Object () { [native code] } uses memory.Memory is released by the Destructor.
Returning TypesIt has different return types.There is no return type for it.
Special SymbolThe special symbol is not required when declaring constructors in the C++ programming language.A specific sign, the tilde symbol, is necessary when defining a destructor in the C++ programming language.
Number of UseIn our program, we can utilize many constructors.The program cannot have more than one destructor.
Way of DeclarationTo create a function Object() { [native code] }, use the following declaration: class Name { ………. public Name ([parameter list]) { ………………. } };To create a destructor, use the following declaration: class Name { …………….; …………….; public: ~abc();  { …………         };

Related Topics

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.

Data Hiding in C++

C++ : High-performance apps can be made using the cross-platform language C++. Bjarne Stroustrup created C++ as an addition to the C language. Programmers have extensive control over memory and system...

3 minutes read.

Unary Operators in C++

Unary operators in C++ Unary operator: is operations that function to produce a new value on a single operand. a) unary minus: A minus operator modifies the argument's symbol. A positive number...

3 minutes read.

Queue in C++

What is Queue? As the name suggests, the queue is the type of data structure that follows the FIFO (First In - First Out) mechanism. In simple words, it is...

4 minutes read.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

3 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

Initialization of Data Members

In this tutorial, we'll look at how to initialise static member variables in C++. Static members, such as functions or variables, can be added to C++ classes. After declaring the...

1 minute read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

Palindrome using For loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 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++ Switch

In C++, an expression or variable can be tested against a range of constant values using a switch statement, which is a control flow statement. It offers a productive method...

4 minutes read.