Constructor & Destructor | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Constructor & Destructor

so i was coding the Singleton Design pattern which states that only one object of a class is allowed. i was doing some things and I made user defined constructors and destructors. so what i was doing create object, display it and then destroy it. but output sequence was: 1.message of constructor 2. message of destructor 3. msg i was printing What is happening here? Why destructor gets called immediately after calling constructor?

1st Nov 2016, 6:01 PM
Syed Muhammad Dawoud Sheraz Ali
Syed Muhammad Dawoud Sheraz Ali - avatar
5 Answers
+ 3
Good Question, A constructor in C++ is called just after the creation of an object of that class . it's basically used for initialising data members of an object class sample { int data; //constructor sample(){ data=10; // just some value cout<<"data initialised successfully"; } //Destructor ~sample(){ cout<<"\nthe object out of scope"; } void disp(){ cout<<"\n display function called "; } }; void main() { sample obj; // statement 1 obj.disp(); // statement 2 } in the above give program when statement 1 is executed the object obj is created in memory and the constructor is called and when the statement 2 is executed the disp() member function of obj is called and AFTER execution of the statement 2 we can see that object obj is no longer used in program right , then the object obj is said to be out of SCOPE and By definition a Destructor is executed when an object goes out of its scope output will be: data initialised successfully display function called the object out of scope
2nd Nov 2016, 7:18 AM
Paul P Joby
Paul P Joby - avatar
+ 2
that is supposed to happen. but i am explicitly deleting object by delete operator. thats what causing problem.. i cant figure out how to tackle that situation.
2nd Nov 2016, 7:47 AM
Syed Muhammad Dawoud Sheraz Ali
Syed Muhammad Dawoud Sheraz Ali - avatar
+ 1
Can you type the code? If you are deleting object with delete it means you are calling its destructor.
2nd Nov 2016, 8:25 AM
Wojciech Skibiński
Wojciech Skibiński - avatar
0
delete this; add this statement to any member function of class sample class sample{ void deleteobj(){ delete this; } };
2nd Nov 2016, 8:34 AM
Paul P Joby
Paul P Joby - avatar
0
i can do like this. but i really want to destroy object using destructor. and i cant post code as it is huge. i can tell what i am doing. Create Stack Push Something Display Delete Stack( by delete). Output is like: Object Created Object Deleted Stack Content Displayed.
2nd Nov 2016, 12:11 PM
Syed Muhammad Dawoud Sheraz Ali
Syed Muhammad Dawoud Sheraz Ali - avatar