What is the use of constructor and destructor in c++? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

What is the use of constructor and destructor in c++?

15th Feb 2018, 1:37 PM
Prankur Singrol
Prankur Singrol - avatar
4 Answers
+ 2
Uses of constructor- to overcome difficulty,it is best to have objects initialized automatically when they are created.to accomplish,java provides for special member functions,called class constructor,which are invoked automatically by the compiler Uses of destructor- when the desteuctor gets invoked the object is deinitialized,i.e., memory is freed to be reclaimed.it is invoked automatically by the compiler In simple words,we can say that constructor used to construct the object and destructor used to destroy the object..... ......hope this help
15th Feb 2018, 1:51 PM
Harsh Agrawal
Harsh Agrawal - avatar
+ 1
Constructors "construct" (create) an instance of an object. It will initialize the variables for you, and in the case of immutable objects this is the only time those values can be set. Destructors are for cleaning up any memory you may have allocated or in some cases updating static variables. For example, say you declare class Puppy that takes a path to an image in it's constructor. It uses this to create a buffer to store the image, and also increments the number of puppies created. The deconstructor will get rid of the image buffer and decrement the puppy count. (Sorry if the below code doesn't compile, I don't work with C++ often enough) static int puppies; byte* image; Puppy(string puppyImagePath) { ++puppies; fstream fimg = fopen(puppyImagePath, "r"); // Forgot to think about the image size image = new byte[100]; fgets (image, 100 , fimg ) fclose(fimg) } ~Puppy() { --puppies; delete image; }
15th Feb 2018, 1:58 PM
Jesse Bayliss
Jesse Bayliss - avatar
+ 1
Working : Constructor is a special member function whose task is to initialise an object of it's class. & Destructor is a special member function whose task is to destroy the object created by constructor. Which gets called automatically when program ends.
24th Apr 2018, 12:54 PM
Jayesh Patil
Jayesh Patil - avatar
15th Feb 2018, 1:40 PM
Sudarshan Rai
Sudarshan Rai - avatar