+ 3
What is the use of constructor and destructor in c++?
4 ответов
+ 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
+ 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;
}
+ 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.
- 1
trick and tip for begginer
https://www.sololearn.com/discuss/468962/?ref=app